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

给你一囗甜甜゛ 提交于 2019-12-20 17:16:04

问题


I am using Express for web services and I need the responses to be encoded in 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?


回答1:


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.



来源:https://stackoverflow.com/questions/31661449/express-js-how-to-set-a-header-to-all-responses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!