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

我可能是错的,但我无法在任何文档中find它。 我试图设置全球范围内的任何响应的内容types,并像这样做:

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

由于某种原因,这是行不通的。 你知道我在做什么错吗? 分别在每种方法中设置它,但我想在全球范围内…

试试这个 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(); }); 

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

 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)