Node.js + Socket.io |在服务器上设置自定义标头 [英] Node.js + Socket.io | Set custom headers on the server
问题描述
我将Helmet与Express结合使用,从服务器端设置了一些安全性HTTP标头.当使用以下命令在node.js应用程序顶部呈现客户端页面时,可以很好地做到这一点:
I use Helmet with Express to set quite some security HTTP headers from the server side. This is nicely done, when rendering client pages on top of the node.js app, using:
var app = express();
app.use(helmet());
..
res.render("pages/index", data);
索引页面上的所有资源都将带有头盔"标头.不幸的是,socket.io会执行自己的标头管理.因此,/socket.io/之后的所有内容都将具有不安全的/自己的标头.例如此处:
All the resources on the index page will have the Helmet headers. Unfortunately, socket.io does its own header management. So, anything that comes after /socket.io/ will have insecure/its own headers. For example here:
<https_path>/socket.io/socket.io.js
<https_path>/socket.io/?EIO=3&transport=polling&t=Lj4CFnj&sid=ILskOFWbHUaU6grTAAAA
因此,我想为所有socket.io项手动设置自定义标头.
Hence, I want to set custom headers for all socket.io items manually.
这就是我需要socket.io的方式(仅摘录):
This is how I require socket.io (excerpt only):
/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
)};
"extraHeaders"选项不起作用,我猜想它只能与socket.io-client一起使用.我做了很多谷歌搜索,但是运气不好.
The "extraHeaders" option doesn´t work, I guess it could only with socket.io-client. I did large amount of googling around, but not luck on this.
还环顾了如何使用socket.request(显然,它对标头有所帮助,根据:此处),但我也无法弄清楚.
Also looked around how to use socket.request (apparently it helps with headers, according to: here), but I couldn´t figure that out either.
你们能帮忙吗?
推荐答案
extraHeaders选项将按以下方式工作,因为您需要删除"transports:['polling']"(如果使用的话),并使用以下模式.这对我有用,并且能够发送自定义标头.
extraHeaders options will work as below, as you need to remove "transports: ['polling']," in case you are using, and use below pattern. This worked for me, and was able to send custom headers.
使用的软件包:-"socket.io-client":"^ 2.2.0",
package used :- "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
}
}
}
})
参考:- https://socket.io/docs/client-api/#With-extraHeaders
这篇关于Node.js + Socket.io |在服务器上设置自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!