Why am I getting this error message?
This is the only route via post. As far as I can see there is no other place where a header is sent.
I also don't understand why body.content evaluates to undefined,even though an object is sent and the header is set to json. By the way, the body parser or app.use(bodyParser.json()) didn't do anything.
"express": "^4.17.3"
I am thankful for help
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);
});
CodePudding user response:
.end
terminates the response. If you call .end
, you can't send anything afterwards. Just remove that part and call .json
to send the data to the client, without killing the response in the middle.
if (!body.content) {
return res.status(400).json({ error: "missing content" });
}