JavaScript - Fetch API



什麼是 Fetch API?

JavaScript Fetch API 是一個 Web API,允許 Web 瀏覽器向 Web 伺服器發出 HTTP 請求。在 JavaScript 中,Fetch API 在 ES6 版本中引入。它是 XMLHttpRequest (XHR) 物件的替代方案,用於向伺服器發出 'GET'、'POST'、'PUT' 或 'DELETE' 請求。

瀏覽器的 window 物件預設包含 Fetch API

Fetch API 提供了 fetch() 方法,可用於非同步訪問網路上的資源。

fetch() 方法允許你向伺服器發出請求,並返回一個 Promise。之後,你需要解析 Promise 以獲取從伺服器接收的響應。

語法

你可以按照以下語法在 JavaScript 中使用 fetch() API:

window.fetch(URL, [options]);
OR
fetch(URL, [options]);

引數

fetch() 方法接受兩個引數。

  • URL − 你需要發出請求的 API 端點。

  • [options] − 這是一個可選引數。它是一個物件,包含方法、標頭等作為鍵。

返回值

它返回一個 Promise,你可以使用 'then...catch' 塊或非同步方式來解決。

使用 'then...catch' 塊處理 Fetch() API 響應

JavaScript fetch() API 返回一個 Promise,你可以使用 'then...catch' 塊來處理它。

按照以下語法使用帶有 'then...catch' 塊的 fetch() API。

fetch(URL)
.then(data => {
   // Handle data
})
.catch(err=> {
   // Handle error
})

在上面的語法中,你可以在 'then' 塊中處理 'data',在 'catch' 塊中處理錯誤。

示例

在下面的程式碼中,我們使用 fetch() API 從給定的 URL 獲取資料。它返回一個 Promise,我們使用 'then' 塊來處理。

首先,我們將資料轉換為 JSON 格式。之後,我們將資料轉換為字串並在網頁上打印出來。

<html>
<body>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById('output');
      const URL = 'https://jsonplaceholder.typicode.com/todos/5';
      fetch(URL)
	  .then(res => res.json())
	  .then(data => {
	     output.innerHTML += "The data from the API is: " + "<br>";
	  	 output.innerHTML += JSON.stringify(data);
   	  });
   </script>
</body>
</html>

輸出

The data from the API is:
{"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}

非同步處理 Fetch() API 響應

你也可以使用 async/await 關鍵字非同步地解決 fetch() API 返回的 Promise。

語法

使用者可以按照以下語法使用 async/await 關鍵字和 fetch() API。

let data = await fetch(URL);
data = await data.json();

在上面的語法中,我們使用 'await' 關鍵字來停止程式碼執行,直到 Promise 完成。之後,我們再次使用帶有 data.json() 的 'await' 關鍵字來停止函式的執行,直到它將資料轉換為 JSON 格式。

示例

在下面的程式碼中,我們定義了 getData() 非同步函式,使用 fetch() API 從給定的 URL 獲取待辦事項列表資料。之後,我們將資料轉換為 JSON 並將輸出列印到網頁上。

<html>
<body>
<div id = "output"> </div>
<script>
   async function getData() {
      let output = document.getElementById('output');
      let URL = 'https://jsonplaceholder.typicode.com/todos/6';
      let data = await fetch(URL);
      data = await data.json();
      output.innerHTML += "The data from the API is: " + "<br>";
      output.innerHTML += JSON.stringify(data);
   }
   getData(); 
</script>
</body>
</html>

輸出

The data from the API is:
{"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}

Fetch() API 的選項

你也可以將包含選項作為鍵值對的物件作為第二個引數傳遞。

語法

按照以下語法將選項傳遞給 Fetch() API。

fetch(URL, {
    method: "GET",
    body: JSON.stringify(data),
    mode: "no-cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
        "Content-Type": "application/json",
    },
    redirect: "follow",
})

選項

這裡,我們提供了一些要傳遞給 fetch() API 的選項。

  • method − 它根據你想要發出哪種型別的請求,取值為 'GET'、'POST'、'PUT' 和 'DELETE' 方法。

  • body − 用於以字串格式傳遞資料。

  • mode − 出於安全原因,它取值為 'cors'、'no-cors'、'same-origin' 等。

  • cache − 它取值為 '*default'、'no-cache'、'reload' 等。

  • credentials − 它取值為 'same-origin'、'omit' 等。

  • headers − 你可以使用此屬性將標頭傳遞到請求中。

  • redirect − 如果你希望使用者在請求完成之後重定向到其他網頁,可以使用 redirect 屬性。

示例:發出 GET 請求

在下面的程式碼中,我們將“GET”方法作為選項傳遞給了 fetch() API。

Fetch() API 從給定的 API 端點獲取資料。

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let options = {
         method: 'GET',
      }
      let URL = "https://dummy.restapiexample.com/api/v1/employee/2";
      fetch(URL, options)
         .then(res => res.json())
         .then(res => {
            output.innerHTML += "The status of the response is - " + res.status + "<br>";
            output.innerHTML += "The message returned from the API is - " + res.message + "<br>";
            output.innerHTML += "The data returned from the API is - " + JSON.stringify(res.data);
         })
         .catch(err => {
            output.innerHTML += "The error returned from the API is - " + JSON.stringify(err);
         })
   </script>
</body>
</html>

輸出

The status of the response is - success
The message returned from the API is - Successfully! Record has been fetched.
The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}

示例(發出 POST 請求)

在下面的程式碼中,我們建立了一個包含 emp_name 和 emp_age 屬性的 employee 物件。

此外,我們建立了一個包含 method、headers 和 body 屬性的 options 物件。我們將 'POST' 用作 method 的值,並將 employee 物件轉換為字串後用作 body 值。

我們使用 fetch() API 向 API 端點發出 POST 請求以插入資料。發出 POST 請求後,您可以在網頁上看到響應。

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let employee = {
         "emp_name": "Sachin",
         "emp_age": "30"
      }
      let options = {
         method: 'POST', // To make a post request
         headers: {
            'Content-Type': 'application/json;charset=utf-8'
         },
         body: JSON.stringify(employee)
      }
      let URL = "https://dummy.restapiexample.com/api/v1/create";
      fetch(URL, options)
         .then(res => res.json()) // Getting response
         .then(res => {
            output.innerHTML += "The status of the request is : " + res.status + "<br>";
            output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
            output.innerHTML += "The data added is : " + JSON.stringify(res.data);
         })
         .catch(err => {
            output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
         })
   </script>
</body>
</html>

輸出

The status of the request is : success
The message returned from the API is : Successfully! Record has been added.
The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}

示例(發出 PUT 請求)

在下面的程式碼中,我們建立了 'animal' 物件。

此外,我們建立了 options 物件。在 options 物件中,我們添加了 'PUT' 方法、headers 和 animal 物件作為 body。

之後,我們使用 fetch() API 更新給定 URL 上的資料。您可以看到成功更新資料的輸出響應。

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let animal = {
         "name": "Lion",
         "color": "Yellow",
         "age": 10
      }
      let options = {
         method: 'PUT', // To Update the record
         headers: {
            'Content-Type': 'application/json;charset=utf-8'
         },
         body: JSON.stringify(animal)
      }
      let URL = "https://dummy.restapiexample.com/api/v1/update/3";
      fetch(URL, options)
         .then(res => res.json()) // Getting response
         .then(res => {
            console.log(res);
            output.innerHTML += "The status of the request is : " + res.status + "<br>";
            output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
            output.innerHTML += "The data added is : " + JSON.stringify(res.data);
         })
         .catch(err => {
            output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
         })
   </script>
</body>
</html>

輸出

The status of the request is : success
The message returned from the API is : Successfully! Record has been updated.
The data added is : {"name":"Lion","color":"Yellow","age":10}

示例(發出 DELETE 請求)

在下面的程式碼中,我們向給定的 URL 發出 'DELETE' 請求,以使用 fetch() API 刪除特定資料。它返回包含成功訊息的響應。

<html>
<body>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById("output");
      let options = {
         method: 'DELETE', // To Delete the record

      }
      let URL = " https://dummy.restapiexample.com/api/v1/delete/2";
      fetch(URL, options)
		 .then(res => res.json()) // After deleting data, getting response
		 .then(res => {
			output.innerHTML += "The status of the request is : " + res.status + "<br>";
			output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
			output.innerHTML += "The data added is - " + JSON.stringify(res.data);
         })
		 .catch(err => {
		    output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
		 })
   </script>
</body>
</html>

輸出

The status of the request is : success
The message returned from the API is : Successfully! Record has been deleted
The data added is - "2"

使用 Fetch() API 的優勢

以下是使用 fetch() API 與第三方軟體或 Web 伺服器互動的一些好處。

  • 簡單的語法 − 它提供了一種簡單的語法來向伺服器發出 API 請求。

  • 基於 Promise − 它返回 Promise,您可以使用 'then...catch' 塊或 'async/await' 關鍵字非同步地解決它。

  • JSON 處理 − 它具有將字串響應資料轉換為 JSON 資料的內建功能。

  • 選項 − 您可以使用 fetch() API 向請求傳遞多個選項。

廣告