如何在Node.js中全局设置内容类型(快速) [英] How to set content type globally in node.js (express)
本文介绍了如何在Node.js中全局设置内容类型(快速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可能是错的,但是在任何文档中都找不到。
我试图为任何响应全局设置内容类型,并且这样做:
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();
});
在定义我的路线之前。
// 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...
推荐答案
尝试此(适用于Express 4.0):
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();
});
这篇关于如何在Node.js中全局设置内容类型(快速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文