【问题标题】:In Node.js/Express, how do I automatically add this header to every "render" response?在 Node.js/Express 中,如何自动将此标头添加到每个“渲染”响应中?
【发布时间】:2011-10-03 10:04:38
【问题描述】:

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

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

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

X-XSS-Protection: 0

如何自动添加响应头?

【问题讨论】:

    标签: javascript node.js http express url


    【解决方案1】:

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

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

    【讨论】:

    • 这是大家现在应该用的。
    • 是的,这是 Express 4 中的方法。始终使用app.use
    • 比例外的答案好多了。
    • 注意res.set is an alias 是这里使用的方法 -- res.header -- 是别名的函数
    【解决方案2】:
    // global controller
    app.get('/*',function(req,res,next){
        res.header('X-XSS-Protection' , 0 );
        next(); // http://expressjs.com/guide.html#passing-route control
    });
    

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

    【讨论】:

    • 啊,这个好像更好
    • 如果你真的想为所有调用添加 header 参数,这比将中间件调用添加到每个路由要短得多。
    • 因此,通过将其添加为第一个控制器,我所有其他控制器的响应中都会包含该标头?
    • Afaik 是的,因此可以通过多个控制器路由响应。
    • 这已经过时了,见下文。
    【解决方案3】:

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

    实施

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

    测试

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

    Dev 依赖项(用于测试工作)

    % npm install --save-dev mocha hippie
    

    相关文档

    【讨论】:

      【解决方案4】:

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

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

      应该可以。

      【讨论】:

        【解决方案5】:

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

        例如:

        //...
        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
           // ...
        });
        

        【讨论】:

          【解决方案6】:

          使用middleware...

          app.use(function (req, res, next) {
            res.header("Access-Control-Allow-Origin", "*")
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
            next()
          })
          

          但请确保您您的 API 方法之前使用它。像这样:

          const app = express()
          
          // middleware
          app.use(function (req, res, next) {
            res.header("Access-Control-Allow-Origin", "*")
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
            next()
          })
          
          // api
          app.get('/user', (req, res, next) => {
            service.doSomething
              .then(data => res.send(data))
              .catch(next)
          })
          
          app.use(handleError)
          

          我花了一段时间才弄明白。我没有在任何地方看到它,所以添加它以补充以前的答案。

          【讨论】:

          【解决方案7】:

          我想指出,这些答案都没有真正回答这个问题;该问题具体与呈现响应有关;例如对于这样的应用:

          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 没有专门做这件事的钩子。目前唯一的选择是组织你的代码,这样你就不必这样做了,例如

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

          ...它允许您按照其他一些答案的建议进行操作,并添加通用中间件来设置标题。

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-15
          • 1970-01-01
          • 1970-01-01
          • 2013-04-17
          • 2021-12-28
          • 1970-01-01
          • 2021-02-17
          • 1970-01-01
          相关资源
          最近更新 更多