我如何使用NodeJS从客户端获取套接字的标头请求

Bob*_* JS 1 sockets node.js

我对这件事很陌生。我只是想知道是否可以获取Web套接字客户端请求标头。我在服务器端使用node.js:

  • 使用ExpresJS可以得到类似以下的标头:

    router.post('/', function (req, res, next) {
        console.log(req.headers);
    
    Run Code Online (Sandbox Code Playgroud)

    });

  • 使用Web套接字,可能吗?

    var WebSocket = require('ws');
    var ws = new WebSocket('ws://www.host.com/path');
    ws.on('open', function open() {
         // how to get the headers
         ws.send('something');
    });
    
    Run Code Online (Sandbox Code Playgroud)

有可能的?谢谢

gen*_*nry 5

WebSockets没有标题,但是它们的升级请求有。

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {

  console.log(ws.upgradeReq.headers);

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});
Run Code Online (Sandbox Code Playgroud)

请注意,您不能将标题设置为ws请求的一部分。