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