首页 > 解决方案 > 使用 express-session 在 express-ws 中存储会话

问题描述

我正在编写一个使用 express-ws 具有 websocket 路由的服务器端脚本,例如:

/init - 当网站在 onload 函数上加载时调用。在 /init 路由中,我正在设置一些会话变量

/request - 当任何请求向服务器发出时调用,例如单击按钮。我会在这里做一些后端处理

问题是虽然调用两个路由时会话 ID 相同。我在/init路由中初始化的会话变量在向/request路由发出的请求中找不到。

下面是服务器端代码:

const express = require('express');
const app = express();
const fs = require('fs');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressWs = require('express-ws')(app);
const session = require('express-session');
const cors = require('cors');

const sessVariables = JSON.parse(fs.readFileSync('session-variables.json').toString());

app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'crack',
    cookie: { secure: false, maxAge: 3600000 }
}))

app.get('/init',(req, res)=>{
    req.session.sessId = 0; //storing the variable here
    console.log('websocket server is up');
    res.status(200).send();
})

app.ws('/request',(client, req)=>{
    console.log(client);
    client.on('message',(data)=>{
        console.log(req.session)
        console.log(data, req.session.id, req.session.sessId); //sessId blank undefined
    })
})

app.listen(3000,()=>{console.log('Server started at port 3000')});

客户端脚本

window.onload = function(){  //calling the init route to store the session
    $.ajax({
        type: 'GET',
        url: 'http://localhost:3000/init',
        success: function(){
            console.log('session initialized');
        },
        error: function(){
            console.log('error');
        }
    })
}

function sendText(){ //calling the function on a button click
    console.log(document.getElementById('txtsendtext').value);
    postData();
}

var Channel = new WebSocket('ws://localhost:3000/request/');

Channel.onopen = function(event){
    console.log(event);
}

function postData(){
    Channel.send('data');
}

更新:会话 id 在 init 调用和之后的 websocket 调用中是不同的,但是在 websocket 调用之后会话 id 仍然存在并且在页面刷新时再次调用 init 并存储 sessId,我也可以在 websocket 调用中访问它。我在页面重新加载时获取会话变量,然后它仍然存在。

为什么我会为 /init 和 /request 获得不同的会话 ID?


已解决:需要将 ajax 调用异步设置为 false 以等待 ajax 调用设置会话 ID。

标签: node.jsexpresssessionexpress-sessionws

解决方案


推荐阅读