javascript 如何在 node.js (express) 中全局设置内容类型

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

How to set content type globally in node.js (express)

javascriptnode.jsexpresscontent-type

提问by Cristian Boariu

I might be wrong but I wasn't able to find this in any documentation. I am trying to set content type globally for any response and did it like:

我可能错了,但我无法在任何文档中找到它。我正在尝试为任何响应全局设置内容类型,并且这样做:

    // Set content type GLOBALLY for any response.
  app.use(function (req, res, next) {
    res.contentType('application/json');
    next();
  });

before defining my routes.

在定义我的路线之前。

 // Users REST methods.
  app.post('/api/v1/login', auth.willAuthenticateLocal, users.login);
  app.get('/api/v1/logout', auth.isAuthenticated, users.logout);
  app.get('/api/v1/users/:username', auth.isAuthenticated, users.get);

For some reason this doesn't work. Do you know what I am doing wrong? Setting it in each method separately, works but I want it globally...

出于某种原因,这不起作用。你知道我做错了什么吗?分别在每种方法中设置它,工作,但我想要它全局......

回答by A.B

Try thisfor Express 4.0 :

在 Express 4.0 上试试这个

// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
  res.header("Content-Type",'application/json');
  next();
});

回答by Cristian Boariu

Found the issue: this setting has to be put BEFORE:

发现问题:此设置必须放在之前:

app.use(app.router)

so the final code is:

所以最终的代码是:

// Set content type GLOBALLY for any response.
app.use(function (req, res, next) {
  res.contentType('application/json');
  next();
});

// routes should be at the last
app.use(app.router)