I'm trying to POST a JSON object using fetch.
From what I can understand, I need to attach a stringified object to the body of the request, e.g.:
fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
When using jsfiddle's json echo I'd expect to see the object I've sent ({a: 1, b: 2}
) back, but this does not happen - chrome devtools doesn't even show the JSON as part of the request, which means that it's not being sent.
I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:
To use it you have the variable
api
and 4 methods:And within an
async
function:Example with jQuery:
After spending some times, reverse engineering jsFiddle, trying to generate payload - there is an effect.
Please take eye (care) on line
return response.json();
where response is not a response - it is promise.jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42
With ES2017
async/await
support, this is how toPOST
a JSON payload:Can't use ES2017? See @vp_art's answer using promises
The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.
This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.
That code works fine - it is POSTing the JSON correctly, it just cannot be seen.
that's not working because that is not the correct format for JSfiddle's echo.
The correct code is:
For endpoints accepting JSON payloads, the original code is correct
From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.
For non-json you don't have to use form data. You can simply set the
Content-Type
header toapplication/x-www-form-urlencoded
and use a string:An alternative way to build that
body
string, rather then typing it out as I did above, is to use libraries. For instance thestringify
function fromquery-string
orqs
packages. So using this it would look like:This is related to
Content-Type
. As you might have noticed from other discussions and answers to this question some people were able to solve it by settingContent-Type: 'application/json'
. Unfortunately in my case it didn't work, my POST request was still empty on the server side.However, if you try with jQuery's
$.post()
and it's working, the reason is probably because of jQuery usingContent-Type: 'x-www-form-urlencoded'
instead ofapplication/json
.