I keep getting undefined when I try to console.log(req.body.title). Also when I console.log(req.body) I only receive an empty {}.
I am using React for the frontend and express for the backend. The post request is coming from:
function handleClick(event) {
event.preventDefault();
const newPost = {
title: input.title,
content: input.content,
};
axios.post("http://localhost:5000/new", newPost).then(console.log(newPost));
}
At the server.js this is my post handler
app.post("/new", (req, res) => {
console.log(req.body);
});
I keep getting undefined when I try to console.log(req.body.title).
See the API reference for request.body :
By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
You have no such middleware. You need to set one (which matches the format of the data you are sending - JSON in this case) up as per the examples in that section of the documentation).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.