ExpressJS & Websocket & session sharing

后端 未结 5 1381
情书的邮戳
情书的邮戳 2020-12-01 09:30

I\'m trying to make a chat application based on Node.js. I\'d like to force websocket server (ws library) to using ExpressJS session system. Unfortunately, I\'ve got stuck.

5条回答
  •  盖世英雄少女心
    2020-12-01 09:48

    I found this works for me. Not sure it's the best way to do this though. First, initialize your express application:

    // whatever your express app is using here...
    var session = require("express-session");
    var sessionParser = session({
        store: session_store,
        cookie: {secure: true, maxAge: null, httpOnly: true}
    });
    app.use(sessionParser);
    

    Now, explicitly call the session middleware from the WS connection. If you're using the express-session module, the middleware will parse the cookies by itself. Otherwise, you might need to send it through your cookie-parsing middleware first.

    If you're using the websocket module:

    ws.on("request", function(req){
        sessionParser(req.httpRequest, {}, function(){
            console.log(req.httpRequest.session);
            // do stuff with the session here
        });
    });
    

    If you're using the ws module:

    ws.on("connection", function(req){
        sessionParser(req.upgradeReq, {}, function(){
            console.log(req.upgradeReq.session);
            // do stuff with the session here
        });
    });
    

    For your convenience, here is a fully working example, using express, express-session, and ws:

    var app = require('express')();
    var server = require("http").createServer(app);
    var sessionParser = require('express-session')({
        secret:"secret",
        resave: true,
        saveUninitialized: true
    });
    app.use(sessionParser);
    
    app.get("*", function(req, res, next) {
        req.session.working = "yes!";
        res.send("");
    });
    
    var ws = new require("ws").Server({server: server});
    ws.on("connection", function connection(req) {
        sessionParser(req.upgradeReq, {}, function(){
            console.log("New websocket connection:");
            var sess = req.upgradeReq.session;
            console.log("working = " + sess.working);
        });
    });
    
    server.listen(3000);
    

提交回复
热议问题