Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-13 13:37:02
Original
440 people have browsed it

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'
      }
      Copy after login
  • 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',
        },
      };
      Copy after login
  • Encode Form Parameters:

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

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

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

      fetch('https://example.com/login', obj)
        .then(function(res) {
          // Do stuff with result
        }); 
      Copy after login
  • 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'
          })
      });
      Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template