Socket.io无法使用transportOptions

时间:2018-09-06 08:41:08

标签: javascript express socket.io

我正在尝试使用transportOptions解析其他变量,但出现错误:

注意:当使用不起作用的代码时,甚至没有到达服务器端代码。

index.js:83 OPTIONS http://127.0.0.1:3000/socket.io/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YjZjM2MzMGQ0YTQyNDIyNzE5MjhjOWIiLCJpYXQiOjE1MzYyMTg4NDcsImV4cCI6MTU5NjIxODc4N30.5eGEA9X7-x95M17rdqYvrVuwQ6rQ6kRKHGx-me6lnOg&EIO=3&transport=polling&t=MMk1XIV 400 (Bad Request)
chat1.html:1 Failed to load http://127.0.0.1:3000/socket.io/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YjZjM2MzMGQ0YTQyNDIyNzE5MjhjOWIiLCJpYXQiOjE1MzYyMTg4NDcsImV4cCI6MTU5NjIxODc4N30.5eGEA9X7-x95M17rdqYvrVuwQ6rQ6kRKHGx-me6lnOg&EIO=3&transport=polling&t=MMk1XIV: Response for preflight does not have HTTP ok status.

这就是我尝试使用的方式:

const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YjZjM2MzMGQ0YTQyNDIyNzE5MjhjOWIiLCJpYXQiOjE1MzYyMTg4NDcsImV4cCI6MTU5NjIxODc4N30.5eGEA9X7-x95M17rdqYvrVuwQ6rQ6kRKHGx-me6lnOg";
const chatId = '5b893a24fe8ad11b42cd1a2e';

不起作用:

const socket = io("http://127.0.0.1:3000", {
 query: {
  token: jwt
   },
            transportOptions: {
                polling: {
                    extraHeaders: {
                        'chatid': chatId
                    }
                }
            }
        });

什么起作用:

const socket = io("http://127.0.0.1:3000", {
                query: {
                    token: jwt
                },
            });

服务器端:

io.sockets.use(async (req, next) => {
  await socketUtil.validateJwt(req, next);
});
// Other file
export const validateJwt = async (socket, next) => {
  try {
    const token = socket.handshake.query.token;
    const valid = await isValidJwt(token);
    if (valid) {
      return next();
    }
    return next(new Error('Invalid JWT: ' + token));
  } catch (e) {
    return next(new Error('Internal server error: ' + e));
  }
};

0 个答案:

没有答案