简体   繁体   English

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

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

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... 在每个方法中单独设置它,但是我想要全局...

Try this for Express 4.0 : 试试对于快递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();
});

Found the issue: this setting has to be put BEFORE: 发现问题:此设置必须放在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM