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

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...