Reputation: 31
I am trying to send data to a server (local rest API) from react using post request, if i send an object like this:
{key:"value"}
then i get this at the server:
{ '{"key":"value"}': '' }
It's converting the whole object into key-value pair. How can i solve this issue?
axios.post('http://localhost:5000/animals', JSON.stringify(data))
.then((response)=>{
console.log(response);
});
If I don't stringify, then I get an empty object at the server, but if I do stringify, then I get this sort of object as mentioned above. Is there any way to convert it back to a normal object?
Upvotes: 2
Views: 782
Reputation: 816414
It looks like the server expects to get data in application/x-www-form-urlencoded
encoding, not application/json
.
Why?
application/x-www-form-urlencoded
encoded data looks like
key1=value1&key2=value2&....
But values are optional, so
key1&key2=value2
works too.
You are sending {"key":"value"}
which to the server looks like a key without a value. Since it looks like you have control over the server, change the server implementation to parse the request body as JSON instead. How to do that depends on the framework you are using on the server.
If you are using express.js, use bodyParser.json()
. Alternatively send the data application/x-www-form-urlencoded
encoded, not as JSON, as suggested by Chinedu.
Upvotes: 1
Reputation: 63
Performing a POST request with axios
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Can you try constructing the data you want to send as the above exam, send to your api and see if the dummy data comes. No json parse or stringfy needed. Are you using body-parser middleware in your nodejs express app?
Upvotes: 0