Home > Web Front-end > JS Tutorial > How to Send Form Data with Fetch API Using `application/x-www-form-urlencoded`?

How to Send Form Data with Fetch API Using `application/x-www-form-urlencoded`?

Linda Hamilton
Release: 2024-11-03 18:30:29
Original
339 people have browsed it

How to Send Form Data with Fetch API Using `application/x-www-form-urlencoded`?

Posting Form Data with Fetch API

Posing form data with the Fetch API utilizes
FormData, which inherently uses the multipart/form-data format. If you seek to send data using "Content-Type": "application/x-www-form-urlencoded", there are two options:

Creating an URL-encoded Body:

<code class="js">fetch("api/xxx", {
    body: "[email protected]&password=pw",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "post"
})</code>
Copy after login

Using URLSearchParams:

To construct a URLSearchParams object from a form element, you can iterate through the elements or use the following conversion method:

<code class="js">const data = new URLSearchParams(new FormData(formElement));
fetch("api/xxx", {
    method: 'post',
    body: data,
})</code>
Copy after login

Note that defining a Content-Type header is unnecessary when using URLSearchParams.

Decoding Multipart/Form-Data in the Controller:

Depending on your backend implementation, you may need to decode the multipart/form-data body. Refer to your desired framework's documentation for specific decoding procedures.

The above is the detailed content of How to Send Form Data with Fetch API Using `application/x-www-form-urlencoded`?. For more information, please follow other related articles on the PHP Chinese website!

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