我正在使用sails.js实现一个nodejs应用程序。我希望我的用户仅通过https进行交流。因此,为此,我需要按照自己的方式配置服务器,以便在每个响应中都添加标头“ Strict-Transport-Security”,“ max-age = 31536000”,以告知浏览器仅与HSTS通信。现在如何修改我将从Sails js发送的每个响应标头,我搜索了文档但没有找到任何帮助。
策略仅应用于您在中显式分配给它们的控制器config/policies.js
。
而不是使用策略,请尝试直接在中添加快速中间件config/express.js
(如果尚不存在,请创建文件)。该中间件适用于所有控制器。格式如下:
// config/express.js
"use strict";
exports.express = {
customMiddleware: function (app) {
app.use(function hsts(req, res, next) {
res.setHeader("Strict-Transport-Security", "max-age=31536000");
next();
});
}
}
如果您要使用多个快速自定义中间件,我的建议是将每个中间件功能保留在其自己的文件中。我将提供一个示例,将您的中间件与接受某些选项的其他中间件一起使用。
// config/express.js
"use strict";
var hsts = require('../lib/middleware/hsts');
var staticguard = require('../lib/middleware/staticguard');
exports.express = {
customMiddleware: function (app) {
// ordering of middleware matters!
app.use(hsts);
app.use(staticguard(/^\/protected\/.*$/));
}
}
// lib/middleware/hsts.js
"use strict";
module.exports = function hsts(req, res, next) {
res.setHeader("Strict-Transport-Security", "max-age=31536000");
next();
}
// lib/middleware/staticguard.js
"use strict";
module.exports = function (regex) {
return function (req, res, next) {
if (!regex.test(req.url)) {
return next();
}
res.end('you are not allowed!');
}
};
如果您尝试让多个文件在“ express.customMiddleware”命名空间上导出一个功能,那么我相信只有最后加载的文件的middleWare才能起作用。我还没有尝试过。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句