Reputation: 453
I'm having trouble sending information from the client side to the server side.
In my application I have a form that I want to submit to my server. Because I am using a lib to auto generate my form from a json schema file, I'll have to manually submit the form, basically make a post
request with my object. So far so good, however my request reaches the backend with an empty body.
Client post request:
const test = {
name: "hello"
}
axios.post("http://localhost:8000/my-route/test", test)
.then(res => console.log("res.data", res.data));
Server route definition
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(cors());
/* ... */
app.post("/my-route/:type", (req, res) => {
if (!req.params.type) {
res.send({
err: "Please provide type"
});
} else {
console.log('req.body', req.body);
res.send({
sucess: "Generating type " + req.params.type
});
}
});
My log on the backend generates req.body {}
instead of req.body { name: "hello" }
If I decide to JSON.stringify(test)
, then my log becomes req.body { '{"name":"hello"}': '' }
, which is not really want I intend.
Upvotes: 0
Views: 40
Reputation: 78920
The axios request is sending a JSON payload. However, your server isn't parsing JSON; it's only parsing URL-encoded bodies. You'll want to add this middleware:
app.use(bodyParser.json());
Because you don't have that parser, your bodyParser.urlencoded(...)
middleware is populating req.body
with just the empty object.
Upvotes: 2