错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 headers | body.content 未定义
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client | body.content undefined
为什么我会收到此错误消息?
这是通过 post 的唯一路线。
据我所知,没有其他地方可以发送 header。
我也不明白为什么 body.content 评估为未定义,即使发送了 object 并且 header 设置为 json。顺便说一下,body 解析器或 app.use(bodyParser.json()) 什么也没做。
"快递": "^4.17.3"
感谢您的帮助
const express = require("express");
const app = express();
app.use(express.json());
app.post("/api/persons/", (req, res) => {
const body = req.body;
//if body has no data return here
console.log(body.content);
if (!body.content) {
return res.status(400).end().json({ error: "missing content" });
}
//generate entry in list
const person = {
number: body.number,
name: body.name,
id: generateID(),
};
persons = persons.concat(person);
res.json(person);
});
.end
终止响应。如果您调用 .end
,之后您将无法发送任何内容。只需删除该部分并调用 .json
即可将数据发送到客户端,而不会在中间终止响应。
if (!body.content) {
return res.status(400).json({ error: "missing content" });
}
为什么我会收到此错误消息?
这是通过 post 的唯一路线。 据我所知,没有其他地方可以发送 header。
我也不明白为什么 body.content 评估为未定义,即使发送了 object 并且 header 设置为 json。顺便说一下,body 解析器或 app.use(bodyParser.json()) 什么也没做。
"快递": "^4.17.3"
感谢您的帮助
const express = require("express");
const app = express();
app.use(express.json());
app.post("/api/persons/", (req, res) => {
const body = req.body;
//if body has no data return here
console.log(body.content);
if (!body.content) {
return res.status(400).end().json({ error: "missing content" });
}
//generate entry in list
const person = {
number: body.number,
name: body.name,
id: generateID(),
};
persons = persons.concat(person);
res.json(person);
});
.end
终止响应。如果您调用 .end
,之后您将无法发送任何内容。只需删除该部分并调用 .json
即可将数据发送到客户端,而不会在中间终止响应。
if (!body.content) {
return res.status(400).json({ error: "missing content" });
}