session.id 发生变化,socket.io 不匹配

session.id changes and socket.io doesn't match

我 运行 webpack-dev-server localhost:8000 我的应用和 express+socket.io 在我的 api 端口 3000 上。我在 webpack.config.js 中代理了对 socket.io 的请求:

devServer: {
    proxy: {
        '/socket.io': {
            target: 'http://localhost:3000',
            ws: true
        }
    }
}

但是,不仅 express 中的会话 ID 与 socket.io 不匹配,而且 express 中的会话 ID 每次请求都会更改:

服务器:

let app = require('express')();
let session = require('express-session')({
    secret: 'panopticon',
    resave: true,
    saveUninitialized: true
});
let server = require('http').createServer(app);
let io = require('socket.io')(server);

//session middleware
app.use(session);
io.use(require('express-socket.io-session')(session, {
    autoSave: true
}));

let i=0;

app.get('/socket.io', (req, res) => {
    console.log(i++, req.session.id);
    //0 'ShgnU91kCZzC7xHP9B57ZtsCbwi3XjdB'
    //1 'qLsYYpRZXpyoUrcKzF6K7uoAIKtE9oCh'

    res.send();
});

io.on('connection', socket => {
    console.log(socket.handshake.session.id);
    //MRUYZMVstMh6ssNrq9LP-Z4vTaT5SZcs
});

客户:

//connect to socket
let socket = io();
//make two requests to /socket.io
fetch('socket.io').then(() => fetch('socket.io'));

我让它工作的唯一方法是先向 localhost:3000:

发出 AJAX 请求
fetch('http://127.0.0.1:3000', {
    credentials: 'include'
});

在响应中使用以下处理程序:

app.use('/', (req, res) => {
    res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8080');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.sendStatus(200);
});

GitHub Gist