Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express 4 Routes Using Socket.io

Having a rough time adding Socket.io in my Express 4 Routes. In my routes/index.js I have:

var express = require('express');
var router = express.Router();

/* GET 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 is undefined. I have seen several examples of how to do this, but none that worked for me. Any help would be appreciated.

like image 923
Andrew Garcia Avatar asked Apr 26 '15 00:04

Andrew Garcia


1 Answers

You need to pass your socket.io variable to the router module so that it has access. You could do this by wrapping your module in a function call.

var express = require('express');
var router = express.Router();

/* GET 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 you import this route you would call this function like: require(./routefile)(io)

Here's a good article about creating modules that require being passed a variable: Node.Js, Require and Exports

like image 176
Logan Tegman Avatar answered Oct 04 '22 15:10

Logan Tegman