Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...