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\"
...
...
// devel
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()
})