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

How to POST x-www-form-urlencoded Data with Fetch?

Susan Sarandon
Release: 2024-11-12 08:53:02
Original
528 people have browsed it

How to POST x-www-form-urlencoded Data with Fetch?

POSTing x-www-form-urlencoded Data with Fetch

In the realm of web development, HTTP requests often carry form-encoded data to servers. To achieve this using the Fetch API, let's explore how to construct such a request.

Consider the scenario where you have parameters like user name, password, and grant type that need to be sent as form-encoded data to a server. You've set up the request with the appropriate headers, but how can you incorporate the parameters?

To do so, you can harness the power of URLSearchParams. Here's how:

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

The URLSearchParams object serves as a container for your parameters. It automatically URL-encodes the values, making them ready for transmission. By setting the Content-Type header appropriately, your request now carries the encoded data to the server.

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