在Node.js/Express中,如何自动将此标题添加到每个"渲染"响应中?

TIM*_*MEX 33 javascript url http node.js express

我有很多这些"控制器":

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

注意res.render?我想将此标头添加到我制作的每个响应标头中:

X-XSS-Protection: 0

如何自动添加响应标头?

Fra*_*sas 71

您可能希望将app.use与您自己的中间件一起使用:

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

  • 这是每个人现在应该使用的东西. (4认同)
  • 是的,这是Express 4中的方法.总是使用`app.use` (4认同)

BGe*_*sen 65

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

只需确保这是您添加的第一个控制器,订单很重要.


Wil*_*III 12

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

履行

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

测试

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

Dev Dependencies(用于测试工作)

% npm install --save-dev mocha hippie
Run Code Online (Sandbox Code Playgroud)

相关文件


pky*_*eck 7

您可以像这样创建自己的中间件方法:

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

然后将您的路线更改为......

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

应该管用.