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
Release: 2024-11-21 08:28:14
Original
915 people have browsed it

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'
    };
    Copy after login
  2. Set the request headers and method:

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

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

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

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

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!

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