Get: Transfer JSON data
P粉348915572
P粉348915572 2023-08-20 11:57:23
0
2
579
<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>
P粉348915572
P粉348915572

reply all(2)
P粉458725040

I think your problem is that jsfiddle can only handle form-urlencoded requests. But the correct way is to pass the correct json as the request body:

fetch('https://httpbin.org/post', {
  method: 'POST',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.json())
  .then(res => console.log(res));
P粉819937486

Using ES2017’s async/await support, here’s how to POST JSON data:

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template