socket.io-client如何在连接时设置请求头

我试图设置一个HTTP头,当socket.io客户端发出连接请求。 有没有办法做到这一点?

这是我在做什么:

// 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选项。

例如:

 var socket = io("http://localhost", { extraHeaders: { Authorization: "Bearer authorization_token_here" } }); 

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

看起来客户端不支持设置标题 ,因为不是所有的传输都允许设置标题。

这个由facundoolano 发布的文章详细介绍了一种不需要在查询string中放置auth令牌的authentication方法。

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

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

截至2.0.0 / 2017-01-22版本的engine.io-client 支持

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

然而在这一点上,socket.io-client并没有被更新来支持这个function,所以几天之后可能会使这个传奇结束,直到那个时候使用下面的指令: https : //facundoolano.wordpress.com/2014/10/11 /更好的validation换sockets-IO-没有查询string/

自从socket.io 1.0以来,此信息已被弃用

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

handshakeData对象包含以下信息:

 { 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 } 

以上信息和更深入的解释可在此文档页面上find 。