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

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

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...

回答1:

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


回答2:

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) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!