node.js - 授权数据中未定义 Socket.IO 查询对象

标签 node.js angularjs socket.io

我正在尝试使用 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() and io.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/

相关文章:

javascript - 如何为浏览器客户端设置 RabbitMQ 绑定(bind)?

node.js - Rails 项目中的 Node 模块可能会缓存旧版本?

Node.js 快速重定向到远程 URL 一直失败(CORS)

javascript - 如何在 AngularJS e2e 测试中测试拖放功能

AngularJS 多指令资源争用

ios - 如何在自签名证书上使用 Socket-IO-Swift 进行连接?

node.js - session 从express bat中删除,而不是从socket.io中删除

javascript - 这个 protobuf 解码有什么问题?

c++ - Node js 服务器和 c++ 客户端套接字 io 连接,无法发出或读取数据

css - 像密码输入一样设计我的文本输入