javascript - Express 4 Routes Using Socket.io -
having rough time adding socket.io in express 4 routes. in routes/index.js have:
var express = require('express'); var router = express.router(); /* home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'express' }); }); router.post('/message', function(req, res) { console.log("post request hit."); // res.contenttype('text/xml'); console.log(appjs); io.sockets.emit("display text", req); // res.send('<response><sms>'+req.body+'</sms></response>'); }); module.exports = router;
but io undefined. have seen several examples of how this, none worked me. appreciated.
you need pass socket.io variable router module has access. wrapping module in function call.
var express = require('express'); var router = express.router(); /* home page. */ var returnrouter = function(io) { router.get('/', function(req, res, next) { res.render('index', { title: 'express' }); }); router.post('/message', function(req, res) { console.log("post request hit."); // res.contenttype('text/xml'); console.log(appjs); io.sockets.emit("display text", req); // res.send('<response><sms>'+req.body+'</sms></response>'); }); return router; } module.exports = returnrouter;
then, whever import route call function like: require(./routefile)(io)
here's article creating modules require being passed variable: node.js, require , exports
Comments
Post a Comment