如何从websocket客户端请求中获取参数

时间:2017-06-27 13:16:23

标签: node.js websocket

我正在尝试授权ws://token:@url的设置参数如何在服务器中从此请求中获取令牌参数。

1 个答案:

答案 0 :(得分:2)

我已经看了websocket库,这就是我提出来的:

// You need to disable `autoAcceptConnections`...
let wss = new WebSocketServer({ httpServer : server, autoAcceptConnections : false });

// ...so the `request` event is fired, which is needed to access the url parameters
wss.on('request', function(req) {
  // Parse the requested URL:
  let url = require('url').parse(req.httpRequest.url);

  // Assume that the token is passed as path:
  // ws://url/TOKEN
  let token = url.pathname.substring(1); // .substring(1) to strip off the leading `/`

  // Validate token (implementation-dependent):
  if (! isValidToken(token)) return req.reject();

  // Accept the request.
  return req.accept();
});