When utilizing the Fetch API to submit form data, there are two main formats to consider:
When using FormData to construct the request body, the data will automatically be sent in the multipart/form-data format. This is a default behavior of FormData and cannot be modified.
To send the data in application/x-www-form-urlencoded format, you have a few options:
1. URL-Encoded String:
<code class="javascript">fetch("api/xxx", { body: "[email protected]&password=pw", headers: { "Content-Type": "application/x-www-form-urlencoded", }, method: "post", });</code>
2. URLSearchParams Object:
<code class="javascript">const data = new URLSearchParams(); data.append("email", "example@email.com"); data.append("password", "mypassword"); fetch("api/xxx", { body: data, method: "post", });</code>
Note that specifying the Content-Type header is not necessary when using URLSearchParams, as it automatically sets the correct content type.
3. URLSearchParams from FormData:
<code class="javascript">const data = new URLSearchParams(new FormData(formElement)); fetch("api/xxx", { body: data, method: "post", });</code>
This option allows you to pass the FormData object directly to create the URLSearchParams object. However, it may have limited browser support, so be sure to test it thoroughly before using it.
The above is the detailed content of How do you send form data with Fetch API in different formats?. For more information, please follow other related articles on the PHP Chinese website!