[英]In Node.js/Express, how do I automatically add this header to every “render” response?
我有很多這些“控制器”:
app.get('/',function(req,res){
var stuff = { 'title': 'blah' };
res.render('mytemplate',stuff);
});
注意res.render? 我想將此標頭添加到我制作的每個響應標頭中:
X-XSS-Protection: 0
如何自動添加響應標頭?
您可能希望將app.use與您自己的中間件一起使用:
app.use(function(req, res, next) {
res.header('X-XSS-Protection', 0);
next();
});
// global controller
app.get('/*',function(req,res,next){
res.header('X-XSS-Protection' , 0 );
next(); // http://expressjs.com/guide.html#passing-route control
});
只需確保這是您添加的第一個控制器,訂單很重要。
對於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);
});
});
% npm install --save-dev mocha hippie
您可以像這樣創建自己的中間件方法:
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);
});
應該管用。
我發現在路由中間件期間注入默認標頭的另一個好地方。 這樣,路由器實例控制的所有路由都將接收標頭。
例如:
//...
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'));
目前尚不清楚如何僅向HTML響應添加標題(例如,CSP標題,這可能非常詳細)。 Express沒有專門做那個鈎子。 目前唯一的選擇是組織您的代碼,以便您不必例如
app.use(jsonRouter);
app.use(htmlRouter);
...允許您像其他一些答案一樣建議,並添加通用中間件來設置標題。
使用中間件 ......
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)
我花了一段時間來搞清楚。 我沒有看到它在任何地方提到過,所以加上這個來補充以前的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.