关于node.js:socket.io-client建立连接时如何设置请求标头

socket.io-client how to set request header when making connection

我试图在socket.io客户端发出连接请求时设置http标头。 有没有办法做到这一点?

这是我在做什么:

1
2
3
4
5
6
7
8
9
// server side
var io = socketio(server);

io.use(function (socket, next) {
  // authorize using authorization header in socket.request.headers
});

// client side
var socket = io();  // i'm trying to set an authorization header in this http reqeust

有任何想法吗? 谢谢。


如果使用的是socket.io-client> = 1.4,则可以使用extraHeaders选项。

例如:

1
2
3
4
5
var socket = io("http://localhost", {
  extraHeaders: {
    Authorization:"Bearer authorization_token_here"
  }
});

engine.io-client是socket.io-client的后端,于2015-11-28引入了extraHeaders支持。


客户端似乎不支持设置标头,因为并非所有传输都允许设置标头。

facundoolano的这篇文章详细介绍了身份验证的解决方法,该方法不需要将auth令牌放入查询字符串中。

可以在https://github.com/invisiblejs/socketio-auth中找到他的解决方法模块。

让我想知道为什么在服务器端,socket.io允许访问请求标头...


从2.0.0版开始/ 2017-01-22 engine.io-client支持

1
[feature] Allow extraHeaders to be set for browser clients in XHR requests (#519)

但是,此时尚未对socket.io-client进行更新以支持此功能,因此可能需要几天的时间才能结束此传奇,直到此时使用以下说明:https://facundoolano.wordpress.com/2014/10/11 /对套接字进行更好的身份验证-没有查询字符串/


从socket.io 1.0开始不推荐使用此信息

授权有两种方法:全局或命名空间(思考路由)。全局方法是通过io.set('authorization', function (handshakeData, callback)配置调用在服务器上设置的。

handshakeData对象包含以下信息:

1
2
3
4
5
6
7
8
9
10
{
   headers: req.headers       // <Object> the headers of the request
 , time: (new Date) +''       // <String> date time of the connection
 , address: socket.address()  // <Object> remoteAddress and remotePort object
 , xdomain: !!headers.origin  // <Boolean> was it a cross domain request?
 , secure: socket.secure      // <Boolean> https connection
 , issued: +date              // <Number> EPOCH of when the handshake was created
 , url: request.url          // <String> the entrance path of the request
 , query: data.query          // <Object> the result of url.parse().query or a empty object
}

以上信息和更深入的说明可在此文档页面上找到。


" transportOptions"选项可用于在socket.io请求中发送额外的标头。我也在这里解释了:

Node.js + Socket.io |在服务器上设置自定义标头