Fetch API - 傳送 GET 請求



Fetch API 提供了一個介面,用於非同步管理與 Web 伺服器之間請求和響應。它提供了一個 fetch() 方法來非同步獲取資源或向伺服器傳送請求,而無需重新整理網頁。使用 fetch() 方法,我們可以執行各種請求,例如 POST、GET、PUT 和 DELETE。在本文中,我們將學習如何使用 Fetch API 傳送 GET 請求。

傳送 GET 請求

GET 請求是一種 HTTP 請求,用於從給定資源或 Web 伺服器檢索資料。在 Fetch API 中,我們可以透過在 fetch() 函式中指定方法型別或不指定任何方法型別來使用 GET 請求。

語法

fetch(URL, {method: "GET"})
.then(info =>{
   // Code
})
.catch(error =>{
   // catch error
});

這裡在 fetch() 函式中,我們在方法型別中指定了 GET 請求。

或者

fetch(URL)
.then(info =>{
   // Code
})
.catch(error =>{
   // catch error
});

在這裡,在 fetch() 函式中,我們沒有指定任何方法型別,因為預設情況下 fetch() 函式使用 GET 請求。

示例

在下面的程式中,我們將從給定的 URL 中檢索 id 和標題,並在表格中顯示它們。因此,為此,我們定義了一個帶 URL 的 fetch() 函式,從中我們檢索資料和 GET 請求。此函式將從給定的 URL 中檢索資料,然後使用 response.json() 函式將資料轉換為 JSON 格式。之後,我們將在表格中顯示檢索到的資料,即 id 和標題。

<!DOCTYPE html>
<html>
<body>
<script>
   // GET request using fetch()function
   fetch("https://jsonplaceholder.typicode.com/todos", {
      // Method Type
      method: "GET"})
   
   // Converting received data to JSON
   .then(response => response.json())
   .then(myData => {
      // Create a variable to store data
      let item = `<tr><th>Id</th><th>Title</th></tr>`;
   
      // Iterate through each entry and add them to the table 
      myData.forEach(users => {
         item += `<tr>
         <td>${users.id} </td>
         <td>${users.title}</td>        
         </tr>`;
      });
      // Display output
      document.getElementById("manager").innerHTML = item;
   });
</script>
<h2>Display Data</h2>
<div>
   <!-- Displaying retrevie data-->
   <table id = "manager"></table>
</div>
</body>
</html>

輸出

Send GET Requests

結論

這就是我們如何使用 Fetch API 傳送 GET 請求,以便我們可以從給定的 URL 請求特定資源或文件。使用 fetch() 函式,我們還可以根據我們的需求自定義 GET 請求。現在,在下一篇文章中,我們將學習如何傳送 POST 請求。

廣告