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

How to Submit x-www-form-urlencoded POST Requests with Fetch?

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 08:28:14936browse

How to Submit x-www-form-urlencoded POST Requests with Fetch?

POSTing x-www-form-urlencoded Request with Fetch

To submit form-encoded parameters to a server using Fetch, you can utilize the following steps:

  1. Define the request parameters:

    const params = {
      'userName': '[email protected]',
      'password': 'Password!',
      'grant_type': 'password'
    };
  2. Set the request headers and method:

    var obj = {
      method: 'POST',
      headers: {
     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
    };
  3. Encode the parameters using the URLSearchParams interface:

    const encodedParams = new URLSearchParams();
    params.forEach((value, key) => encodedParams.append(key, value));
  4. Specify the body of the request:

    obj.body = encodedParams.toString();
  5. Finally, make the request:

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

This process effectively encodes and includes the form-encoded parameters in the POST request, ensuring their submission to the server in a format compatible with your API.

The above is the detailed content of How to Submit x-www-form-urlencoded POST 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