Home  >  Article  >  Web Front-end  >  How to Post Form Data as \"application/x-www-form-urlencoded\" with Fetch API?

How to Post Form Data as \"application/x-www-form-urlencoded\" with Fetch API?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 05:28:02871browse

How to Post Form Data as

Posting Form Data with the Fetch API

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:

  1. 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.

  2. 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!

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
Previous article:Strapi — WhyNext article:Strapi — Why