[英]Node.js + Socket.io | Set custom headers on the server
I use Helmet with Express to set quite some security HTTP headers from the server side.我使用 Helmet 和 Express 从服务器端设置了相当多的安全 HTTP 标头。 This is nicely done, when rendering client pages on top of the node.js app, using:
这做得很好,在 node.js 应用程序顶部渲染客户端页面时,使用:
var app = express();
app.use(helmet());
..
res.render("pages/index", data);
All the resources on the index page will have the Helmet headers.索引页面上的所有资源都将具有 Helmet 标题。 Unfortunately, socket.io does its own header management.
不幸的是,socket.io 有自己的头管理。 So, anything that comes after /socket.io/ will have insecure/its own headers.
所以,在 /socket.io/ 之后的任何东西都会有不安全的/它自己的头文件。 For example here:
例如这里:
<https_path>/socket.io/socket.io.js
<https_path>/socket.io/?EIO=3&transport=polling&t=Lj4CFnj&sid=ILskOFWbHUaU6grTAAAA
Hence, I want to set custom headers for all socket.io items manually.因此,我想手动为所有 socket.io 项目设置自定义标头。
This is how I require socket.io (excerpt only):这就是我需要 socket.io 的方式(仅摘录):
/src/app.js /src/app.js
var express = require("express");
var sio = require("socket.io");
var app = express();
var io = require("./../lib/io.js").initialize(app.listen(REST_PORT, () => {
logger.info("Application ready on port " + REST_PORT + " . Environment: " + NODE_ENV);
}));
/lib/io.js /lib/io.js
exports = module.exports = {};
var sio = require("socket.io");
exports.initialize = function(server) {
var options = {
cookie: false,
extraHeaders: {
"X-Custom-Header-For-My-Project": "Custom stuff",
}
};
io = sio(server, options);
io.on("connection", function(socket) {
// logic
)};
The "extraHeaders" option doesn´t work, I guess it could only with socket.io-client. “extraHeaders”选项不起作用,我想它只能与 socket.io-client 一起使用。 I did large amount of googling around, but not luck on this.
我做了大量的谷歌搜索,但没有运气。
Also looked around how to use socket.request (apparently it helps with headers, according to: here ), but I couldn´t figure that out either.还查看了如何使用 socket.request (显然它有助于标头,根据: here ),但我也无法弄清楚。
Could you guys help?你们能帮忙吗?
extraHeaders options will work as below, as you need to remove "transports: ['polling']," in case you are using, and use below pattern. extraHeaders 选项将如下工作,因为您需要删除“transsports: ['polling']”,以防您正在使用,并使用以下模式。 This worked for me, and was able to send custom headers.
这对我有用,并且能够发送自定义标头。
package used :- "socket.io-client": "^2.2.0",使用的包:-“socket.io-client”:“^2.2.0”,
this.socket = io(environment.host, {
path: `/api/backend/socket.io`,
origins: '*:*',
// transports: ['polling'],
transportOptions: {
polling: {
extraHeaders: {
'authorization': token,
'user-id' : userId
}
}
}
})
Ref:- https://socket.io/docs/client-api/#With-extraHeaders参考:- https://socket.io/docs/client-api/#With-extraHeaders
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.