Node.js + Socket.io | Set custom headers on the server

独自空忆成欢 提交于 2020-01-02 09:39:09

问题


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);

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

Hence, I want to set custom headers for all socket.io items manually.

This is how I require socket.io (excerpt only):

/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

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. 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.

Could you guys help?

来源:https://stackoverflow.com/questions/43261827/node-js-socket-io-set-custom-headers-on-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!