策略仅应用于您在中明确分配给它们的控制器config/policies.js
.
尝试直接添加快速中间件,而不是使用策略config/express.js
,(如果该文件尚不存在,则创建该文件)。该中间件应用于ALL控制器。格式是这样的:
// 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 才能工作。不过我还没试过。