Fetch API - 傳送 PUT 請求



在 Fetch API 中,PUT 請求用於更新或替換伺服器上存在的現有資源或資料。使用 PUT 請求通常會在請求主體中包含要更新的資料。當伺服器收到請求時,它會使用這些資料來更新給定 URL 中存在的現有資源。如果伺服器不包含該資源,則它會使用給定資料建立一個新資源。

語法

fetch(URL, {
   method: "PUT",
   body: {//JSON Data},
   headers:{"content-type": "application/json; charset=UTF-8"}})
.then(info =>{
   // Code
})
.catch(error =>{
   // catch error
});

這裡 fetch() 函式包含以下引數:

  • URL − 它表示我們要獲取的資源。

  • method − 這是一個可選引數。它用於表示請求,例如 GET、POST、DELETE 和 PUT。

  • body − 這也是一個可選引數。當您想要向請求新增主體時,可以使用此引數。

  • headers − 這也是一個可選引數。它用於指定頭部資訊。

示例 1:使用 fetch() 傳送 PUT 請求

在下面的程式中,我們建立一個簡單的指令碼,使用 fetch() 函式透過 PUT 請求更新給定 URL 中的現有資料。這裡我們在給定的 URL 以及頭部資訊中傳送一個 JSON 文件。因此,在收到響應後,檢查響應的狀態。如果響應狀態為 200,則表示資料已成功更新。如果發生錯誤,則 catch 函式會處理該錯誤。

<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<h1>Example of Fetch API</h1>
<script>
   // Update data in the URL using the PUT request
   fetch("https://jsonplaceholder.typicode.com/todos/21", {
      // Using PUT request
      method: "PUT",

      // Body contains replacement data 
      body: JSON.stringify({
         id: 22,
         title: "Hello! Mohina what are you doing?",
      }),
      // Setting headers
      headers:{"Content-type": "application/json; charset=UTF-8"}
   })
   .then(response => {
      // Handle response
      if (response.status == 200){
         console.log("Data updated successfully")
      } else {
         throw new error("Error Found:", response.status)
      }
   })
   // Handle error
   .catch(err=>{
      console.error(err)
   });
</script>
</body>
</html>

輸出

PUT Request

示例 2:使用 fetch() 和 async/await 傳送 PUT 請求

在下面的程式中,我們建立一個指令碼,使用 fetch() 函式和 async/await 透過 PUT 請求更新給定 URL 中的現有資料。這裡我們在給定的 URL 以及頭部資訊中傳送一個 JSON 文件。因此,我們建立了一個名為 modifyData() 的非同步函式。這裡我們使用 await 關鍵字與 fetch() 函式一起使用,以暫停函式的執行,直到返回的 Promise 被解析。在收到響應後,檢查響應的狀態,如果響應狀態為 200,則表示資料已成功更新。如果發生錯誤,則 catch 函式會處理該錯誤。

注意 − 這裡 async/await 結合使用,以同步的方式處理非同步操作。

<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<h1>Example of Fetch API</h1>
<script>
   async function modifyData(){
      try{
         const myRes = await fetch("https://jsonplaceholder.typicode.com/todos/21", {
            // Using PUT request
            method: "PUT",

            // Body contains replacement data 
            body: JSON.stringify({
               id: 24,
               title: "Mina leaves in Delhi",
            })
         });
         // Handling response
         if (myRes.status == 200){
            console.log("Data updated successfully")
         } else {
            throw new error("Error Found:", myRess.status)
         }
      } catch(err){
         console.error(err)
      }
   }
   // Calling the function
   modifyData();
</script>
</body>
</html>

輸出

PUT Request

結論

這就是我們如何使用 PUT 請求更新給定資源中的現有資料。使用它,您還可以使用 fetch() 函式提供的引數向請求新增額外的屬性。現在在下一章中,我們將瞭解如何傳送 JSON 資料。

廣告