Home >Web Front-end >JS Tutorial >How to Send Form Data with Fetch API: Multipart/form-data vs. Application/x-www-form-urlencoded?

How to Send Form Data with Fetch API: Multipart/form-data vs. Application/x-www-form-urlencoded?

DDD
DDDOriginal
2024-11-03 12:51:021092browse

How to Send Form Data with Fetch API: Multipart/form-data vs. Application/x-www-form-urlencoded?

Sending Form Data with Fetch API

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:

  1. String Encoding: Manually encode the form data into an URL-encoded string.
  2. URLSearchParams: Initialize a URLSearchParams object and append each form field's name and value to it. Avoid specifying the Content-Type header explicitly, as the browser will infer it from the URLSearchParams object.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn