Home  >  Q&A  >  body text

Get: Transfer JSON data

<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粉348915572P粉348915572449 days ago543

reply all(2)I'll reply

  • P粉458725040

    P粉4587250402023-08-21 10:51:25

    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));

    reply
    0
  • P粉819937486

    P粉8199374862023-08-21 10:15:17

    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);
    })();

    reply
    0
  • Cancelreply