Express.js - 如何为所有响应设置标头 [英] Express.js - How to set a header to all responses

查看:1092
本文介绍了Express.js - 如何为所有响应设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

Express middleware documentation here.

这篇关于Express.js - 如何为所有响应设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆