node.js - 使用 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。
解决方案
推荐阅读
- d3.js - D3 Js 垂直线与水平阈值线的交点
- firebase - 重新启动 Firebase 服务器时未反映对本地 firebase.json 的更改
- javascript - 当 CSS 变换将元素带入视口时,Intersection Observer 无法正常工作
- python - 从一列中提取多个值到熊猫中的新列
- sql - 在 Firebird 中有效地处理时间序列数据
- java - 使用 Maven 编译具有所有依赖项的 JavaFX jar
- ruby-on-rails - 如何告诉 webpacker 停止加载 .spec.ts 文件
- php - 通过 PDO SELECT 查询填充 MySQL 表行数据的问题
- javascript - 如何对 Wordpress 标题内容进行 A/B 拆分测试?
- r - 条形图清理 x 轴标签