capricorn86 / happy-dom

A JavaScript implementation of a web browser without its graphical user interface
MIT License
3.09k stars 185 forks source link

feat: Adds support for application/x-www-form-urlencoded in Request.formData #1379

Closed tt-public closed 3 months ago

tt-public commented 3 months ago

Currently Request.formData only handles "multipart/form-data", but it seems that it should also support "application/x-www-form-urlencoded" according to the specs. https://fetch.spec.whatwg.org/#dom-body-formdata

Current behavior:

const params = new URLSearchParams();
params.append("d", "data");

const req = new Request("https://example.com", { method: "POST", body: params });

for (const [key, value] of req.headers.entries()) {
    console.log(`${key}: ${value.split(";")[0]}`);
}
// content-type: application/x-www-form-urlencoded

(async () => {
    for (const [key, value] of (await req.formData()).entries()) {
        console.log(`${key}: ${value}`);
    }
    // DOMException [InvalidStateError]: Failed to build FormData object: The "content-type" header isn't of type "multipart/form-data".
})();

The current implementation of Request.formData in happy-dom directly calls a method which seems to be based on toFormData in node-fetch. [source] However, Request.formData in node-fetch only calls toFormData after handling "application/x-www-form-urlencoded" [source], which probably should be reflected in this project too.

Thank you for the awesome project. I hope this helps!