ExpressJS how do I pass objects with state (eg. co

2019-08-07 19:01发布

问题:

This is more of an architectural question than anything. I am working on a project that uses ExpressJS, Angular, and Socket.io and have run into a challenge of trying to persist the socket.io instantiation so other areas can use it.

Let's jump into what I have:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

In the code above, the io variable can be used to create listeners, send messages, etc. In another file I have my routes that are passed the app var:

require('./app/routes')(app);

In my routes I handle requests, and in one case when a POST comes in I want to fire off a message in socket.io to the connected clients. How do I make the io variable accessible to other areas?

Note: I'm using mongoose with mongodb and noticed that "mongoose.connect(db.url);" is called in the server file, and then in other modules I can require the mongoose.js and call models. How do they maintain the connection across the multiple instantiations?

回答1:

Just like you do with app variable, you just pass it

require('./app/routes')(app, io);

and then in the routes, you catch it

module.exports = function(app, io) {

    app.get('something', function(req, res, next) {

        io.emit('something else');

    });

}


回答2:

I'm not sure to really answer to your question but if you need to use sessions in your application you can share the sessions between express routes and socket.io by initializing like this :

var session = require('express-session')({
    secret: 'mysupersessioncode',
    resave: false,
    saveUninitialized: false
});

var io = require("socket.io")(server);
io.use(function (socket, next) {
    session(socket.request, socket.request.res, next);
});

Then you will be able to do this to get your express session into your socket :

io.on('connect', function(socket) {
    var session = socket.request.session; // This is the actual user session using a socket
}

I don't know if it's what you are trying to do when you speak about "persist the socket.io" but I hope it can be useful for you.