携带额外的请求头 extraHeaders

优质
小牛编辑
136浏览
2023-12-01

仅当建立的是轮询连接时才起作用(默认为polling轮询),当使用websocket建立传输时,自定义的请求头将不会被添加,因为WebSockets握手信号不信任自定义的请求头(详细信息可以阅读 WebSocket protocol RFC

const socket = io({
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});

// 服务器端
const io = require('socket.io')();

// 中间件
io.use((socket, next) => {
  let clientId = socket.handshake.headers['x-clientid'];
  if (isValid(clientId)) {
    return next();
  }
  return next(new Error('authentication error'));
});

仅当通过websocket传输时

默认的,长轮询连接会被首次创建,随后升级到更好的传输方式(比如WebSocket)。

如果你喜欢挑战性,这一部分可以被跳过。

const socket = io({
  transports: ['websocket']
});

// on reconnection, reset the transports option, as the Websocket
// connection may have failed (caused by proxy, firewall, browser, ...)
socket.on('reconnect_attempt', () => {
  socket.io.opts.transports = ['polling', 'websocket'];
});

携带自定义的解析器

默认的解析器(详细内容查阅这里Socket.IO custom parsers

const parser = require('socket.io-msgpack-parser'); // or require('socket.io-json-parser')
const socket = io({
  parser: parser
});

// the server-side must have the same parser, to be able to communicate
const io = require('socket.io')({
  parser: parser
});