跳至主要内容

如何与 `express-session` 一起使用

让我们从一个基本应用程序开始

const express = require("express");
const { createServer } = require("node:http");
const { join } = require("node:path");
const { Server } = require("socket.io");
const session = require("express-session");

const port = process.env.PORT || 3000;

const app = express();
const httpServer = createServer(app);

const sessionMiddleware = session({
secret: "changeit",
resave: true,
saveUninitialized: true,
});

app.use(sessionMiddleware);

app.get("/", (req, res) => {
res.sendFile(join(__dirname, "index.html"));
});

app.post("/incr", (req, res) => {
const session = req.session;
session.count = (session.count || 0) + 1;
res.status(200).end("" + session.count);
});

const io = new Server(httpServer);

httpServer.listen(port, () => {
console.log(`application is running at: http://localhost:${port}`);
});

共享会话上下文

可以通过调用来与 Socket.IO 服务器共享会话上下文

io.engine.use(sessionMiddleware);

就这么简单!您现在可以访问 `session` 对象

io.on("connection", (socket) => {
const session = socket.request.session;
});

使用会话 ID

您可以使用会话 ID 来建立 Express 和 Socket.IO 之间的链接

io.on("connection", (socket) => {
const sessionId = socket.request.session.id;

// the session ID is used as a room
socket.join(sessionId);
});

然后,您可以在 `/incr` 处理程序中通知每个连接的客户端

app.post("/incr", (req, res) => {
const session = req.session;
session.count = (session.count || 0) + 1;
res.status(200).end("" + session.count);

io.to(session.id).emit("current count", session.count);
});

注销流程也是如此

app.post("/logout", (req, res) => {
const sessionId = req.session.id;

req.session.destroy(() => {
// disconnect all Socket.IO connections linked to this session ID
io.in(sessionId).disconnectSockets();
res.status(204).end();
});
});

修改会话

由于它不绑定到单个 HTTP 请求,因此必须手动重新加载和保存会话

io.on("connection", (socket) => {
const req = socket.request;

socket.on("my event", () => {
req.session.reload((err) => {
if (err) {
return socket.disconnect();
}
req.session.count++;
req.session.save();
});
});
});

您也可以使用 中间件,它将在每个传入数据包触发

io.on("connection", (socket) => {
const req = socket.request;

socket.use((__, next) => {
req.session.reload((err) => {
if (err) {
socket.disconnect();
} else {
next();
}
});
});

// and then simply
socket.on("my event", () => {
req.session.count++;
req.session.save();
});
});
注意

调用 `req.session.reload()` 会更新 `req.session` 对象

io.on("connection", (socket) => {
const session = socket.request.session;

socket.use((__, next) => {
session.reload(() => {
// WARNING! "session" still points towards the previous session object
});
});
});

处理会话过期

您可能还想定期重新加载会话,以防会话过期(例如,如果客户端在较长时间内未发送任何事件)

const SESSION_RELOAD_INTERVAL = 30 * 1000;

io.on("connection", (socket) => {
const timer = setInterval(() => {
socket.request.session.reload((err) => {
if (err) {
// forces the client to reconnect
socket.conn.close();
// you can also use socket.disconnect(), but in that case the client
// will not try to reconnect
}
});
}, SESSION_RELOAD_INTERVAL);

socket.on("disconnect", () => {
clearInterval(timer);
});
});

跨站点请求的说明

express-session 依赖于 cookie 在浏览器中持久保存会话。因此,如果您的前端域与您的后端域不同(例如,如果您在您的机器上运行 SPA,但在不同的端口上),那么您需要发送适当的 CORS 标头

const cors = require("cors");

const corsOptions = {
origin: ["http://localhost:4200"],
credentials: true
};

// for Express
app.use(cors(corsOptions));

// for Socket.IO
const io = new Server(httpServer, {
cors: corsOptions
});

您还需要在客户端设置 `withCredentials` 选项为 `true`

import { io } from "socket.io-client";

const socket = io("http://localhost:3000", {
withCredentials: true
});

这就是与 `express-session` 的兼容性。感谢您的阅读!

提示

您可以在浏览器中直接运行此示例