Express.js - 如何为所有响应设置 header

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

我正在使用 Express 进行网络服务,我需要将响应编码为 utf-8。

我知道我可以对每个回复执行以下操作:

response.setHeader('charset', 'utf-8');

是否有一种简洁的方法来为 express 应用程序发送的所有响应设置 header 或字符集?

只需使用对所有路由执行的中间件语句:

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

并且,确保在您希望它应用到的任何路由之前注册它:

app.use(...);
app.get('/index.html', ...);

Express 中间件documentation here.