Node.js如何为每个请求设置内容类型标头

Fre*_*nda 2 header http node.js

我想知道如何"Content-Type": "application/json"为传入的每个nodejs表达请求设置标头。

我尝试了这两行,但是如果我自己不添加标题,我的呼叫仍然会失败:

app.use(function(req, res, next) {
    req.header("Content-Type", "application/json");
    res.header("Content-Type", "application/json");
    next();
});
Run Code Online (Sandbox Code Playgroud)

我所有的请求都是json,所以我不希望前端(Anguler)每次向我发送此标头,只要我可以自己从服务器端进行设置。

Ale*_*lex 6

必须使用Response对象.setHeader代替.header

app.use(function(req, res, next) {
    res.setHeader("Content-Type", "application/json");
    next();
});
Run Code Online (Sandbox Code Playgroud)

doc。