首頁  >  問答  >  主體

取得:傳輸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 天前482

全部回覆(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
  • 取消回覆