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.
const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
data.append(pair[0], pair[1]);
}
OR, use the experimental method:
const data = new URLSearchParams(new FormData(formElement));
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".
fetch(url, {
method: 'post',
body: data,
})
.then(…);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3