首頁 >web前端 >js教程 >如何使用 Fetch 發送 x-www-form-urlencoded 請求?

如何使用 Fetch 發送 x-www-form-urlencoded 請求?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-13 13:37:02491瀏覽

How to Send x-www-form-urlencoded Requests with Fetch?

使用Fetch 傳送x-www-form-urlencoded 要求

在Web 開發中,將表單編碼的資料POST 到伺服器是一種常見的操作任務。要使用 Fetch API 完成此操作,需要執行幾個步驟。

  • 定義請求參數:

    • 開始定義您想要 POST 的表單參數。在提供的範例中:

      {
          'userName': '[email protected]',
          'password': 'Password!',
          'grant_type': 'password'
      }
  • 建構請求物件:

    var obj = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
    };
  • 編碼表單參數:

    • body: new URLSearchParams({
          'userName': '[email protected]',
          'password': 'Password!',
          'grant_type': 'password'
      })
    • 執行請求:
    • fetch('https://example.com/login', obj)
        .then(function(res) {
          // Do stuff with result
        }); 
      執行請求:
    • 簡化範例:

      fetch('https://example.com/login', {
          method: 'POST',
          headers:{
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams({
              'userName': '[email protected]',
              'password': 'Password!',
              'grant_type': 'password'
          })
      });
    為了簡單起,見更簡潔的方法就是直接在fetch() 中指定表單參數和header選項:

    有關更多詳細信息,請參閱Mozilla 開發者網絡文檔:https:// developer.mozilla.org/en-US/docs /Web/API/WindowOrWorkerGlobalScope/fetch

    以上是如何使用 Fetch 發送 x-www-form-urlencoded 請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn