Reputation: 9
I have an alert button on the client side with an event listener that is trying to send data to the server. Here is my client side code:
alertBtn.addEventListener("click", () => {
axios
.post("http://localhost:3000/", {
userEmail: "test",
selectedPrice: "test",
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
Here is my express code on the server:
app.post("/", (req, res) => {
console.log(req.body);
res.json({ requestBody: req.body });
});
I am trying to handle the data but the body of the request is just an empty object ({}
).
Upvotes: 0
Views: 761
Reputation: 329
When sending JSON need to set the appropriate headers, as express will only decode the body is the incoming request have the right headers see here
But if you would like the answer upfront its
axios
.post("http://localhost:3000/", {
userEmail: "test",
selectedPrice: "test",
}, {
headers: {
'content-type': 'application/json'
}
})
//By default axios should do this, so maybe middlewares are missing server side?
also as commenter stated im presuming you already set your middlewares infront of this code....
Upvotes: 2