首页  >  问答  >  正文

获取:传输JSON数据

<p>我正在尝试使用fetch方法POST一个JSON对象。</p> <p>根据我的理解,我需要将一个字符串化的对象附加到请求的body中,例如:</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>当使用jsfiddle的JSON echo时,我希望能够看到我发送的对象(<code>{a: 1, b: 2}</code>),但这并没有发生- Chrome开发者工具甚至不显示JSON作为请求的一部分,这意味着它没有被发送。</p>
P粉348915572P粉348915572399 天前481

全部回复(2)我来回复

  • P粉458725040

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

    我认为你的问题是jsfiddle只能处理form-urlencoded请求。但是正确的方法是将正确的json作为请求体传递:

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

    回复
    0
  • P粉819937486

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

    使用ES2017的async/await支持,这是如何进行POST JSON数据的方法:

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

    回复
    0
  • 取消回复