Nodejs 如何为每个请求设置内容类型标头

问题描述 投票:0回答:3

我想知道如何为每个传入的 Nodejs Express 请求设置标头

"Content-Type": "application/json"

我尝试了这两行,但如果我自己不添加标头,我的调用仍然会失败:

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

我所有的请求都是json,所以我不希望前端(Anguler)每次都向我发送这个标头,如果我可以从服务器端自己设置它的话。

node.js http header
3个回答
34
投票

响应对象必须使用

.setHeader
而不是
.header
:

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

文档。


2
投票
res.writeHead(200, {
    "Content-Type": "application/json",
    "Content-Length": "1234...",
});

将标头作为对象发送,这里还必须指定状态代码,

200
表示状态为
OK
,在此处了解有关状态代码的更多信息:HTTP Status Codes

或使用此代码设置单独的标题

res.setHeader("Content-Type", "application/json");

1
投票

要更新请求标头,请在 bodyparser 之前添加以下自定义中间件

app.use(function (req, res, next) {
  req.headers['content-type'] = 'application/json';
  next();
});

如果仍然无法正常工作,请检查客户端发送的“内容类型”的大小写。将“内容类型”放在相同的情况下

© www.soinside.com 2019 - 2024. All rights reserved.