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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6661151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:42:03  来源:igfitidea点击:

In Node.js/Express, how do I automatically add this header to every "render" response?

javascriptnode.jshttpexpressurl

提问by TIMEX

I have many of these "controllers":

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

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

Notice res.render? I want to add this header to every response header I make:

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

X-XSS-Protection: 0

X-XSS-Protection: 0

How can I add that response header automatically?

如何自动添加该响应标头?

回答by Francesc Rosas

You probably want to use app.usewith your own middleware:

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

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

回答by BGerrissen

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

Just make sure this is the first controller you add, order is significant.

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

回答by Wil Moore III

For express 4.x, the idiomatic way is as follows:

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

Implementation

执行

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

Test

测试

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 Dependencies (for tests to work)

开发依赖项(用于测试工作)

% npm install --save-dev mocha hippie

Relevant Documentation

相关文件

回答by pkyeck

you could create your own middleware method like so:

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

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

and then change your routes to sth like this:

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

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

should work.

应该管用。

回答by obrientimothya

I find that another good place to inject default headers is during the Routing Middleware. This way, all routes controlled by the router instance will receive the headers.

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

For example:

例如:

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

回答by user3697417

I'd like to point out that none of these answer actually answer the question; the question is specifically relating to render responses; e.g. for an app like:

我想指出,这些答案都没有真正回答这个问题;该问题特别与渲染响应有关;例如对于像这样的应用程序:

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

It's not clear how to add headers (e.g. CSP headers, which can be very verbose) onlyto your HTML responses. Express doesn't have a hook to specifically do that. The only option at the moment is to organize your code so you don't have to, e.g.

不清楚如何向 HTML 响应添加标头(例如 CSP 标头,可能非常冗长)。Express 没有专门的钩子来做到这一点。目前唯一的选择是组织你的代码,这样你就不必,例如

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

...which allows you to do as some of the other answers suggest, and add generic middleware for setting the headers.

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

回答by Evandro Pomatti

Use a 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()
})

But make sure you use it beforeyour API method. Like this:

但是请确保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)

Took me a while to figure it out. I didn't see it mentioned anywhere so adding this to complement previous answers.

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