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.
Had the same issue - no
body
was sent from a client to a server.Adding
Content-Type
header solved it for me:The top answer doesn't work for PHP7, because it has wrong encoding, but I could figure the right encoding out with the other answers. This code also sends authentication cookies, which you probably want when dealing with e.g. PHP forums:
I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:
Such as the curl request
In case to the remote serve not accept a json file as the body, just send a dataForm:
Such as the curl request
It might be useful to somebody:
I was having the issue that formdata was not being sent for my request
In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.
So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.
Also as other answers suggest that the Content-Type header needs to be correct.
For my request the correct Content-Type header was:
So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is rsolved.
I think your issue is
jsfiddle
can processform-urlencoded
request only.But correct way to make json request is pass correct
json
as a body:If your JSON payload contains arrays and nested objects, I would use
URLSearchParams
and jQuery'sparam()
method.To your server, this will look like a standard HTML
<form>
beingPOST
ed.