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

时间:2015-02-23 10:05:55

标签: javascript node.js express content-type

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

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

在定义路线之前。

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

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

2 个答案:

答案 0 :(得分:17)

对于Express 4.0,请尝试this

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

答案 1 :(得分:3)

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

app.use(app.router)

所以最终的代码是:

// 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)