我想知道如何为传入的每个 nodejs express 请求设置 header "Content-Type": "application/json"
。
我尝试了这两行,但如果我不自己添加 header ,我的调用仍然失败:
app.use(function(req, res, next) {
req.header("Content-Type", "application/json");
res.header("Content-Type", "application/json");
next();
});
我所有的请求都是 json,所以我不希望前端 (Anguler) 每次都向我发送这个 header ,如果我可以从服务器端自己设置的话。
最佳答案
响应对象必须使用 .setHeader
而不是 .header
:
app.use(function(req, res, next) {
res.setHeader("Content-Type", "application/json");
next();
});
关于node.js - Nodejs如何为每个请求设置内容类型 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52812561/