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!