在Node.js / Express中,如何自动将这个头添加到每个“渲染”响应?

我有很多这样的“控制器”:

app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); 

注意res.render? 我想把这个头添加到我所做的每个响应头中:

X-XSS-Protection: 0

我怎样才能自动添加该响应标题?

 // global controller app.get('/*',function(req,res,next){ res.header('X-XSS-Protection' , 0 ); next(); // http://expressjs.com/guide.html#passing-route control }); 

只要确保这是你添加的第一个控制器,顺序是重要的。

你可能想用你自己的中间件使用app.use :

 app.use(function(req, res, next) { res.header('X-XSS-Protection', 0); next(); }); 

对于express 4.x,惯用方式如下:

履行

 // no mount path; executed for every request. app.use(function (req, res, next) { res.set('X-XSS-Protection', 0); next(); }); 

testing

 describe('Response Headers', function () { it('responds with header X-XSS-Protection: 0', function (done) { hippie(app) .get('/any/route/you/can/think/of') .expectHeader('X-XSS-Protection', 0) .end(done); }); }); 

开发依赖关系(testing工作)

 % npm install --save-dev mocha hippie 

相关文件

  • 应用程序级中间件
  • res.set

你可以像这样创build自己的中间件方法:

 addToHeader = function (req, res, next) { console.log("add to header called ... " + req.url); res.header('X-XSS-Protection', '0'); next(); } 

然后改变你的路线,像这样:

 app.get('/', addToHeader, function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); 

应该pipe用。

我发现另外一个注入默认头文件的好地方是在路由中间件期间。 这样,由路由器实例控制的所有路由都将收到报头。

例如:

 //... var router = express.Router(); // middleware for all routes router.use(function(req, res, next) { // inject default headers res.header('cache-control', 'private, max-age=0'); res.header('expires', new Date(Date.now()).toUTCString()); next(); }); // all routes below will now inherit // the middleware's default headers router.get('/users', function(req, res){ // I will return the user list, with default headers // ... }); 

我想指出的是,这些答案都没有回答这个问题。 该问题具体涉及提供答复; 例如对于一个应用程序如:

 const router = require('express').Router(); router.use('/test.json', (req, res) => res.json({ test: 'hi' }); router.use('/test.html', (req, res) => res.render('test')); 

目前还不清楚如何添加标题(例如CSP标题,这可能是非常详细的), 只能给你的HTML响应。 Express没有专门做这个的钩子。 目前唯一的select是组织你的代码,所以你不必,例如

 app.use(jsonRouter); app.use(htmlRouter); 

…它允许你做一些其他的答案build议,并添加通用的中间件来设置标题。