gpt4 book ai didi

node.js - 验证socket.io时无法添加握手参数

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:10 24 4
gpt4 key购买 nike

我正在使用socket.io V1.2.1并尝试遵循official Socket.io authorization wiki page ,但它似乎有点过时(可能是为 0.9 版本编写的),因此在进行一些更改后,这是我用于启动服务器和配置身份验证的代码:

server = http.createServer(app)
io = require('socket.io')(server)
global.io = io
global.liveTopicIo = io.of "/live-topic"
server.listen(3100)
io.set 'authorization', (handshakeData, callback)->
# doing some authentication logic here
# & reading 'currentUser'
if isAuthenticated
handshakeData.user = currentUser
callback null, true
else
callback null, false

liveTopicIo.on "connection", (socket) ->
console.log 'user: ', socket.handshake.user
console.log 'a user connected'

前面的代码打印以下内容

user: undefined

a user connected

那么,为什么我无法向握手数据添加参数? &如何修复此问题以添加当前用户?

最佳答案

基于the migration notes from 0.9 to 1.x ,授权不应该再依赖于set函数,而应该是一个普通的express中间件,所以它应该是这样的:

liveTopicIo.use (socket, next)->
# doing some authentication logic here based on the info
# from socket.handshake & reading 'currentUser'
if isAuthenticated
socket.handshake.user = currentUser
next()
else
next(new Error("Access Denied"))

关于node.js - 验证socket.io时无法添加握手参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com