Home >Web Front-end >JS Tutorial >How to Send x-www-form-urlencoded Requests with Fetch?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 13:37:02483browse

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

The above is the detailed content of How to Send x-www-form-urlencoded Requests with Fetch?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn