Reputation: 65
I am using react(frontEnd) with nodejs (backend), I am trying to send post request from client to sever. .
Here below I sending the request to server, by using axions. I tried without axions simply calling fetch instead.I tired with adding localhost:5000 and without but I it still not working.
FYI , all the data that I am sending are valid and there are as requested.
Here I am trying to handle my request and at least print it to console to verify that my request is as passed valid
result of prints!!!
could you please advise regarding the above ?
After adding body-parser: currently I am getting a undefined object, could you please advise?
Upvotes: 0
Views: 2059
Reputation: 3047
Try This way
const data = {
name: this.state.additionalCost
};
axios
.post(
'/api/processData',
data,
{ headers: { 'Content-Type': 'application/json' } }
)
.then(function(result) {
console.log(result);
});
And use body-parser in express app
import express from 'express';
import bodyParser from 'body-parser';
app.use(bodyParser.json());
Upvotes: 1
Reputation: 4983
You don't need to JSON.stringify
your data from the react axios request.
Here's an example:
const user = {
name: this.state.name
};
axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
.then(res => {
console.log(res);
console.log(res.data);
}
)
For more read Using Axios with React.
Upvotes: 0
Reputation: 3443
Set content type in header and check
axios.post('url', data, {
headers: {
'Content-Type': 'application/json',
}
}
Upvotes: 0