"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-02-07
Browse:548

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.

    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.

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

    fetch(url, {
        method: 'post',
        body: data,
    })
    .then(…);
Latest tutorial More>

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