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

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

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

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

Sending x-www-form-urlencoded Requests with Fetch

In web development, POSTing form-encoded data to a server is a common task. To accomplish this using the Fetch API, a few steps are necessary.

  • Define Request Parameters:

    • Start by defining the form parameters you wish to POST. In the provided example:

      {
          'userName': '[email protected]',
          'password': 'Password!',
          'grant_type': 'password'
      }
  • Construct Request Object:

    • Create a JavaScript object with the necessary request properties:

      var obj = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
      };
  • Encode Form Parameters:

    • To include form-encoded parameters, use a URLSearchParams object:

      body: new URLSearchParams({
          'userName': '[email protected]',
          'password': 'Password!',
          'grant_type': 'password'
      })
  • Execute Request:

    • Finally, execute the request using the newly constructed object:

      fetch('https://example.com/login', obj)
        .then(function(res) {
          // Do stuff with result
        }); 
  • Simplified Example:

    • For simplicity, a cleaner approach is to specify both the form parameters and header directly in the fetch() options:

      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'
          })
      });

Refer to the Mozilla Developer Network documentation for more detailed information: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

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

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