我正在尝试使用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));
}
};