node.js Express.js - 如何为所有响应设置标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31661449/
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-09-02 19:09:09  来源:igfitidea点击:

Express.js - How to set a header to all responses

node.jsexpresshttp-headers

提问by znat

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?

是否有一种干净的方法可以为快速应用程序发送的所有响应设置标头或字符集?

回答by jfriend00

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 中间件文档