Home > Web Front-end > JS Tutorial > How do you send form-encoded data with Fetch API?

How do you send form-encoded data with Fetch API?

Patricia Arquette
Release: 2024-11-13 02:56:02
Original
754 people have browsed it

How do you send form-encoded data with Fetch API?

POSTing Form-Encoded Data Using Fetch

When making POST requests, you might need to include form-encoded data in your payload. Here's how to handle this using the Fetch API:

Solution

You can easily include form-encoded parameters in your request using the URLSearchParams object. Here's an example:

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

This will encode your parameters as 'userName=[email protected]', 'password=Password!', and 'grant_type=password', and append them to the request body.

For more information on the WindowOrWorkerGlobalScope.fetch method, refer to the Mozilla Developer Network documentation: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

The above is the detailed content of How do you send form-encoded data with Fetch API?. 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