關於 Fetch API


Posted by hoyi-23 on 2021-07-03

Fetch

fetch() 是一個位於全域window物件的方法,用來執行送出Request的工作,成功後,回傳一個帶有Response物件的Promise物件。基於Promise,所以也使用.then下去,然後.catch處理錯誤狀況。


關於 JavaScript Promises


fetch() 有兩個參數:

  1. 第一個必要的參數,就是要取得資源的網址。
    使用fetch()不論請求成功還是失敗,都會回傳Promise
  2. 第二個可以選擇性使用,是稱為 init的物件參數,可以傳送一個 init Object 來設定 request。

Get JSON

基本方法

const myData = [];
fetch('Url.json',{method: 'GET'})    //這裡會回傳Promise
  .then(response=> response.json())  //
  .then(data => myData.push(...data)) //const 不能改變數值,因此使用push將資料推入

補充:

  • " ... "三個點在JavaScript中表示 Spread operator。 延伸文章

  • fetch 後方會接 then(),這是 Promise 的特性,資料取得後可在 then 裡面接收。
    六角學院卡斯伯老師的介紹延伸文章

抓錯 catch

需要特別注意的是:
fetch()只要在伺服器有回應的情況下(包含狀態碼是錯誤碼的回應 404;500...),都會回傳Promise物件,除非網路問題或伺服器失連等等,所以使用時還是需要檢查。

如何避免上面的問題:
也就是若伺服器有正確回應,不管是什麼狀態碼,就算是 404 也會將 response 傳入 then 之後的 function 繼續執行,而不會進到 catch。

const myData = [];
fetch('Url.json',{method: 'GET'})    //這裡會回傳Promise
  .then(response => {  
  if (!response.ok) throw new Error(response.statusText) //ok 代表狀態碼在範圍 200-299
  return response.json()
}).then(data => myData.push(...data))  //const 不能改變數值,因此使用push將資料推入
  .catch(function(err) {  
    console.log('Error');// Error :(
})

Fetch後的Response

Fetch 完成後,Response是個 ReadableStream 物件,還需要再透過其他方式來取得資料:

  1. arrayBuffer()
  2. blob()
  3. formData()
  4. json()
  5. text()

回傳Response後,在使用上面其一的方法取得資料就可以囉!

Fetch 包含憑證( credentials )

前面只有介紹到需要帶入 要請求的網址 和 init的物件參數。

  • 想要讓瀏覽器將 credentials 跟著 request 一起送出, 需要在 init object 加上 credentials: 'include'

    fetch('https://example.com', {
    credentials: 'include'
    })
    
  • 如果只想要把 credentials 發送給同源的 URL ,加上credentials: 'same-origin'

// The calling script is on the origin 'https://example.com'

fetch('https://example.com', {
  credentials: 'same-origin'
})
  • 或要確保瀏覽器不會帶著 credentials 請求,可以用 credentials: 'omit'
    fetch('https://example.com', {
    credentials: 'omit'
    })
    

Post JSON

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

上傳檔案可以透過使用HTML <input type="file" /> input element, FormData() 與fetch()。

var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

文章參考:
MDN文章


#Fetch API







Related Posts

this 與 call() / apply() / bind()

this 與 call() / apply() / bind()

關於 React 小書:將 JSX 傳入函式,再把回傳的 JSX 放到頁面

關於 React 小書:將 JSX 傳入函式,再把回傳的 JSX 放到頁面

Day04 git 知己知彼

Day04 git 知己知彼


Comments