简体   繁体   English

Node.js在WebSocket范围上表达标头

[英]Nodejs express headers on the websocket scope

I've got a node.js + express + socket.io app. 我有一个node.js + express + socket.io应用程序。

i want to save the request headers in the socket, to use later. 我想将请求标头保存在套接字中,以备后用。

io.sockets.on('connection', function (socket) {

  socket.headers = {};

  app.get('*', function (req, res) {

    //fetch headers
    socket.headers.ua = req.headers['user-agent'];  

    res.sendfile(__dirname + '/index.html');

  });
  ....etc

but because i am in the app scope, socket isnt defined. 但是因为我在应用程序范围内,所以未定义套接字。 I always get confused with the in and out scope. 我总是对输入和输出范围感到困惑。 i cannot app.get() it, because if another browser connects, the app will be changed, right? 我无法app.get()它,因为如果连接了另一个浏览器,该应用程序将被更改,对吗?

You're doing it wrong. 你这样做是错的。 Every socket has a handshake object with it which contains request headers, domain, host, date etc. If you still want to fetch headers information then do this: 每个套接字都有一个handshake对象,其中包含请求标头,域,主机,日期等。如果您仍要获取标头信息,请执行以下操作:

io.sockets.on('connection', function(socket) {
  console.log(socket.handshake); //This would print handshake object in JSON format
  // to get req-header, do this
  socket.head = socket.handshake.headers['user-agent'];
});

And you can use this property later in some event like: 您可以稍后在某些事件中使用此属性,例如:

socket.on('EventName',function(data){
  console.log(socket.head);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM