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:
fetch("api/xxx", {
body: "[email protected]&password=pw",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "post",
});
2. URLSearchParams Object:
const data = new URLSearchParams();
data.append("email", "[email protected]");
data.append("password", "mypassword");
fetch("api/xxx", {
body: data,
method: "post",
});
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:
const data = new URLSearchParams(new FormData(formElement));
fetch("api/xxx", {
body: data,
method: "post",
});
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.
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