node.js - 在 socket.io 中验证 jwt
问题描述
这是我的登录代码:
router.post("/", async (req, res) => {
const { email, password } = req.body;
console.log(email, password);
try {
if (email && password) {
const accessToken = jwt.sign(email, process.env.TOKEN_SECRET)
res.json(accessToken);
} else res.sendStatus(400);
} catch (error) {
res.sendStatus(500);
}
});
我想在我的其他文件中使用accessToken :
io.on('connection', socket => {
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room, *accessToken*);
socket.join(user.room);
})
谁能告诉我我该怎么做?谢谢!
解决方案
您需要使用中间件功能:
//client side send token
const socket = io({
auth: {
token: "abc"
}
});
//server side
io.use((socket, next) => {
const token = socket.handshake.auth.token;
// ...
});
推荐阅读
- javascript - 单击外部汉堡菜单以使用 javascript 关闭
- powerbi - 带有资源输入的甘特图
- asp.net-core-mvc - ASP.NET Core MVC - 连接字符串和数据库
- python - 如何在 EC2 AWS 上为 Python 脚本添加 cronjob/调度程序?
- laravel - enum() 总是输入一个较小的数字
- docker - 使用 Docker 在 ubuntu 服务器上部署 Strapi
- excel - 从特定列的 lastrow 中选择负列
- python - 保存子类 keras/Tensorflow 模型时的输入兼容性问题,但转换为 tensorflow lite 然后保存工作
- git - 了解分支如何链接到远程分支
- pine-script - 如何在 Tradingview Pinescript 中比较当前数组和最后一个数组?