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
Linda HamiltonOriginal
2024-11-03 18:30:29338browse

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>

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>

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:
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