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

Maybe I'm wrong, but I could not find it in any documentation. I am trying to set the content type globally for any answer and he liked it:

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

before defining 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 does not work. Do you know what I am doing wrong? Installing it in each method separately works, but I want it globally ...

+8
content-type javascript express
source share
2 answers

Try this for 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(); }); 
+13
source share

Problem detected: this parameter must be set 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) 
+3
source share

All Articles