Get: Transfer JSON data
P粉348915572
2023-08-20 11:57:23
<p>I'm trying to POST a JSON object using the fetch method. </p>
<p>According to my understanding, I need to append a stringified object to the body of the request, for example: </p>
<pre class="brush:js;toolbar:false;">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) })
</pre>
<p>When using jsfiddle's JSON echo, I expect to be able to see the object I'm sending (<code>{a: 1, b: 2}</code>), but this doesn't happen - Chrome Development The tool doesn't even show the JSON as part of the request, which means it's not being sent. </p>
I think your problem is that
jsfiddle
can only handleform-urlencoded
requests. But the correct way is to pass the correctjson
as the request body:Using ES2017’s
async/await
support, here’s how toPOST
JSON data: