How to use socket.io in express routes? - node.js

I'm using Express with Socket.io but I can't figure out how to use SocKet.io in Express routes.
I end up doing this in "app.js"
...
...
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var server = http.createServer(app);
var io = require("socket.io").listen(server);
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/cmp', function(request, response) {
var client = new pg.Client("pg://user:pass#127.0.0.1/db_name");
client.connect(function(err) {
// Get the product_id and bid
var product_id = request.body.product_id;
var bid = request.body.bid.split('b')[1];
// If not get the connection
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('select 1 from product_bid where product_id = $1 and number_bid = $2', [product_id, bid], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (result.rowCount == 1) {
// do not insert
} else {
// insert
// Insert to the DB
client.query('insert into product_bid (product_id, number_bid) values ($1, $2)', [product_id, bid], function(err, result) {
if(err) {
return console.error('error running query', err);
}
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
client.end();
});
}
});
});
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
// ---------------
io.on('connection', function(socket){
console.log("alguem se ligou!");
socket.emit('event_from_server', {message: 'conectou-se ao servidor'});
});
How can I define the route to "/cmp" like this and passing the var "io" inside?
app.post('/cmp', routes.cmp);
So that in "/routes/cmp.js" I can do something like this:
exports.cmp = function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
};
Some clues?

How about a higher order function?
exports.cmp = function(io) {
return function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
}
};
and then
app.post('/cmp', routes.cmp(io));
As another option, I'll sometimes format my routes in the following format:
var routes = require('./routes/routes');
routes(app, io);
And then define routes as
module.exports = function(app, io) {
app.post('/cmp', function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
})
};

You can use simple middleware before routes, and then use in res object
app.use((req, res, next) => {
res.io = io
next()
})

Related

Using mongoDB how can i prevent someone from using the same username as someone else?

I have a form where a user is supposed to put in there nickname, the issue is I need the nickname to be unique, in that no one else should be able to make there nickname the same as someone elses. Is there a fix for this using only mongoDB and not mongoose?
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var PORT = 3332;
app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost/gtra", {
useNewUrlParser: true
});
var db = mongoose.connection;
db.once("open", function(cb) {
console.log("connection established");
});
app.post("/addname", (req, res) => {
var name = req.body.pickname;
var data = {
nickname: name
};
db.collection("dat").insertOne(data, function(err, coll) {
if (err) throw err;
console.log("rec estab");
res.redirect("/");
});
});
app.listen(PORT, function() {
console.log("server is up and running using port " + PORT);
});
You can check if there is already a username in the collection, if exists you can throw exception.
app.post("/addname", (req, res) => {
var data = {
nickname: req.body.pickname
};
db.collection("dat").findOne({ nickname: data.nickname }, function(err, doc) {
if (err) throw err;
if (doc) {
return res.status(400).send("Nickname already taken"); //or throw whatever you want
} else {
db.collection("dat").insertOne(data, function(err, coll) {
if (err) throw err;
console.log("rec estab");
res.redirect("/");
});
}
});
});
Another option is creating a unique index on the nickname field.
db.users.createIndex( { "nickname": 1 }, { unique: true } )
Change users to your collection name.

Invalid Input syntax for Integer postgresql error

I am trying to run the delete query from app.js file to postgresql database but every time I am getting error: invalid input syntax for integer: "undefined"
Below is my app.js file code:
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cons = require('consolidate'),
dust = require('dustjs-helpers'),
pg = require('pg-promise'),
pgdb = require('pg'),
app = express();
//DB Connection
const config = {
user: 'Nasreen',
database: 'Inventory1',
password: 'test',
port: 5432 //Default port, change it if needed
};
const pool = new pgdb.Pool(config);
//assign dust engine
app.engine('dust', cons.dust);
//set default ext
app.set('view engine', 'dust');
app.set('views', __dirname + '/views');
//set public folder
app.use(express.static(path.join(__dirname, 'public')));
//Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('SELECT * FROM "Products"', function (err, result) {
if (err) {
return console.error('error running query', err);
}
res.render('index', { Products: result.rows });
done();
});
});
});
app.post('/add', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('INSERT INTO "Products" ("Name", "Purchase_Qty", "Purchase_Rate") VALUES($1, $2, $3)',
[req.body.Name, req.body.Purchase_Qty, req.body.Purchase_Rate]);
done();
res.redirect('/');
});
});
app.delete('/delete/:ID', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('DELETE FROM "Products" WHERE "ID" = $1',
[req.params.ID]);
done();
res.sendStatus(200);
});
});
app.post('/edit', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('UPDATE "Products" SET "Name"= $1, "Purchase_Qty"= $2, "Purchase_Rate"= $3 WHERE "ID"= $4',
[req.body.Name, req.body.Purchase_Qty, req.body.Purchase_Rate, req.body.ID]);
done();
res.redirect('/');
});
})
INSERT is working fine with double quotes for column names and table name but delete and edit wont't work.
Can someone plz help!!
You don't need to quote the tables' names and the columns' names.
Change the delete statement to:
"DELETE FROM Products WHERE ID = '$1'";
Change the update statement to:
"UPDATE Products SET Name= '$1', Purchase_Qty= '$2', Purchase_Rate= '$3' WHERE ID= '$4'";
EDIT:
Try this:
client.query(`DELETE FROM "Products" WHERE "ID" = ${req.params.ID}`);
It's a function overloading for query. Using template string should solve the issue.
Instead of:
client.query('DELETE FROM "Products" WHERE "ID" = $1',[req.params.ID]);

Cannot post membership/login/submit

I have some code to create an account and have a login page and say true or false if you entered the correct details but instead it says 'Cannot post /membership/login/submit'.
my main.js code (the html files are basic and the forms are just standard tags with an action and a method, tell me if you want these)
var app = require('express')();
var http = require('http').Server(app);
var httpuse = require('http');
var io = require('socket.io')(http);
var MongoClient = require('mongodb').MongoClient;
var users = require(__dirname + '/local_js/users.js');
var public = __dirname + "/www/";
var bodyParser = require('body-parser')
var url = "mongodb://localhost:27017/";
const bcrypt = require('bcrypt');
var needle = require('needle');
const saltRounds = 10;
app.use(bodyParser.urlencoded({ extended: false }));
function rand(n) {
Math.floor(Math.random() * (n+1));
}
function getToken(hashedpass, user) {
return hashedpass+"_._"+user;
}
app.get('/', function(req, res){
res.sendFile(public + 'index.html');
});
app.get('/membership/create/form', function(req, res){
res.sendFile(public + 'user/create.html');
});
app.post('/membership/create/submit', function(req, res){
MongoClient.connect(url, function(errdd, db) {
if (errdd) throw errdd;
var dbo = db.db("boaichat");
bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
if (err) {throw err;}
var newUser = { nickname: req.body.nickname, password: hash };
dbo.collection("users").insertOne(newUser, function(errd, ress) {
if (errd) throw errd;
console.log("1 user document inserted");
db.close();
res.send("200 OK");
});
});
});
});
app.get('/membership/login/form', function(req, res) {
res.sendFile(public + 'user/login.html');
});
app.post('membership/login/submit', function(req, res) {
MongoClient.connect(url, function(errdd, db) {
if (errdd) throw errdd;
var dbo = db.db("boaichat");
dbo.collection("users").findOne({nickname: req.body.nickname}, function(err, result) {
if (err) throw err;
if (result) {
bcrypt.compare(req.body.password, result.password, function(err, ress) {
console.log(ress);
res.send(ress);
});
}
});
db.close();
});
});
// IGNORE THIS
app.post('api/v1/getSessionValid', function(req, res) {
let token = req.body.token;
let userInfo = token.split('_._');
if (userInfo[0] && userInfo[1]) {
}
});
io.on('connection', function(socket){
console.log('connection');
socket.on('disconnect', function(){
console.log("disconnection");
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
it says 'Cannot post /membership/login/submit'.
Don't forget the / at the beginning of your route.
// Try this
app.post('/membership/login/submit', ...)
// Instead of
app.post('membership/login/submit', ...)

Express.js nested routes without parameters

I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};

Unable to connect to MongoDB. Please make sure mongod is running on mongodb://localhost:27017/mongo-server

I got this issue when running index.js.
Here is my code:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var url = 'mongodb://localhost:27017/mongo-server';
// Use connect method to connect to the server
MongoClient.connect(url, function(error, db) {
if (error) {
console.error("Unable to connect to MongoDB. Please make sure mongod is running on %s.", url);
process.exit(1);
}
console.log("Connected to MongoDB successfully.");
collectionDriver = new CollectionDriver(db);
});
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
app.get('/:collection', function(req, res) {
var params = req.params;
collectionDriver.findAll(req.params.collection, function(error, objs) {
if (error) { res.send(400, error); }
else {
if (req.accepts('html')) {
res.render('data',{objects: objs, collection: req.params.collection});
} else {
res.set('Content-Type','application/json');
res.send(200, objs);
}
}
});
});
app.get('/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
if (entity) {
collectionDriver.get(collection, entity, function(error, objs) {
if (error) { res.send(400, error); }
else { res.send(200, objs); }
});
} else {
res.send(400, {error: 'bad url', url: req.url});
}
});
app.post('/:collection', function(req, res) {
var object = req.body;
var collection = req.params.collection;
collectionDriver.save(collection, object, function(err,docs) {
if (err) { res.send(400, err); }
else { res.send(201, docs); }
});
});
app.put('/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
if (entity) {
collectionDriver.update(collection, req.body, entity, function(error, objs) {
if (error) { res.send(400, error); }
else { res.send(200, objs); }
});
} else {
var error = { "message" : "Cannot PUT a whole collection" }
res.send(400, error);
}
});
app.delete('/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
if (entity) {
collectionDriver.delete(collection, entity, function(error, objs) {
if (error) { res.send(400, error); }
else { res.send(200, objs); }
});
} else {
var error = { "message" : "Cannot DELETE a whole collection" }
res.send(400, error);
}
});
app.use(function (req,res) {
res.render('404', {url:req.url});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I am new to MongoDB.
first Start Mongo Server
step for that
C:\Program Files\MongoDB\Server\3.2\bin
now write mongod
after running successfully you will see this output
My code for connection
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
make sure to start your mongo server from your terminal or command prompt.
Follow the below steps to start the server:
if mongodb is not installed, install it from https://www.mongodb.com/download-center#community.
you have to create a new directory in your c folder with name called data and inside data create one more directoy called db. These folders are required for your mongodb to save data.
now open terminal or command prompt, navigate inside the bin folder residing in your mongodb folder and enter mongod. this will start your server.

Resources