[英]Express.js - How to set a header to all responses
I am using Express for web services and I need the responses to be encoded in utf-8.我正在将 Express 用于 Web 服务,我需要将响应编码为 utf-8。
I know I can do the following to each response:我知道我可以对每个响应执行以下操作:
response.setHeader('charset', 'utf-8');
Is there a clean way to set a header or a charset for all responses sent by the express application?是否有一种干净的方法可以为 express 应用程序发送的所有响应设置标头或字符集?
Just use a middleware statement that executes for all routes:只需使用对所有路由执行的中间件语句:
// a middleware with no mount path; gets executed for every request to the app
app.use(function(req, res, next) {
res.setHeader('charset', 'utf-8')
next();
});
And, make sure this is registered before any routes that you want it to apply to:并且,确保在您希望它应用到的任何路由之前注册它:
app.use(...);
app.get('/index.html', ...);
Express middleware documentation here . Express 中间件文档在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.