我正在尝试使用 socket.io(版本 1.0+)进行基于 token 的 URL 身份验证,但无法从以下内容读取查询对象:
//server code snippet
io.set('authorization', function (data, accept){
console.log(data.query); //prints undefined
//authentication logic...
});
//client code snippet
angular.module('app')
.factory('socket', function ($rootScope){
var socketProvider = 'http://localhost:3000';
var token = 'testtoken';
var socket = io.connect(socketProvider, {'query': 'token=' + token});
//more factory code for websocket handling...
});
套接字连接成功,我可以使用data._query访问“ protected ”的查询对象,但我不想以这种方式使用它,因为它很脏。
最佳答案
根据migration guide :
The old
io.set()
andio.get()
methods are deprecated and only supported for backwards compatibility.
相反,您可以使用以下内容:
io.use(function(socket, next) {
if (socket.handshake.query.token === 'Your valid token') {
next();
} else {
next(new Error('Your error message for the client'));
}
});
关于node.js - 授权数据中未定义 Socket.IO 查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588004/