Background
When using Fetch API to send form data, it's common to encounter issues related to the Content-Type and boundary used when encoding the data. This article explores the nature of these issues and provides solutions for encoding multipart/form-data vs. application/x-www-form-urlencoded.
FormData and multipart/form-data
As mentioned in MDN's FormData documentation, FormData implicitly encodes data in multipart/form-data format. This format is unsuitable for sending data with a Content-Type of application/x-www-form-urlencoded.
Solution for application/x-www-form-urlencoded
To encode data in application/x-www-form-urlencoded format, you have two options:
Alternative for URLSearchParams
If experimental support is available, you can also pass the FormData object directly to URLSearchParams instead of appending values manually. This approach is still under development and should be tested thoroughly before implementation.
Conclusion
By understanding the mechanics of FormData and the behavior of Fetch API, developers can send form data correctly in multipart/form-data or application/x-www-form-urlencoded format, ensuring proper data transfer and handling on the server side.
The above is the detailed content of How to Send Form Data with Fetch API: Multipart/form-data vs. Application/x-www-form-urlencoded?. For more information, please follow other related articles on the PHP Chinese website!