When using the FormData interface in Fetch API to post form data, it is important to understand its default behavior. By default, it sends data using the "multipart/form-data" format, which is not compatible with the "application/x-www-form-urlencoded" format.
If you want to post form data as "application/x-www-form-urlencoded" using Fetch API, you can follow these steps:
Convert FormData to URLSearchParams: Use a loop to iterate through the FormData object and append each key-value pair to a URLSearchParams object.
<code class="javascript">const data = new URLSearchParams(); for (const pair of new FormData(formElement)) { data.append(pair[0], pair[1]); }</code>
OR, use the experimental method:
<code class="javascript">const data = new URLSearchParams(new FormData(formElement));</code>
Note: Ensure your browser supports the latter method before using it.
Send data using Fetch API: Make a POST request with the body set to the URLSearchParams object. Do not specify a Content-Type header, as the default will be "application/x-www-form-urlencoded".
<code class="javascript">fetch(url, { method: 'post', body: data, }) .then(…);</code>
The above is the detailed content of How to Post Form Data as \'application/x-www-form-urlencoded\' with Fetch API?. For more information, please follow other related articles on the PHP Chinese website!