Skip to content

Commit

Permalink
feat: Adds support for application/x-www-form-urlencoded in Request.f…
Browse files Browse the repository at this point in the history
…ormData
  • Loading branch information
tt-public committed Apr 4, 2024
1 parent 75041b2 commit b447dc9
Showing 1 changed file with 37 additions and 16 deletions.
53 changes: 37 additions & 16 deletions packages/happy-dom/src/fetch/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,29 +304,50 @@ export default class Request implements Request {
* @returns FormData.
*/
public async formData(): Promise<FormData> {
if (this.bodyUsed) {
throw new DOMException(
`Body has already been used for "${this.url}".`,
DOMExceptionNameEnum.invalidStateError
);
}
const type = this[PropertySymbol.contentType];

(<boolean>this.bodyUsed) = true;
if (/multipart/i.test(type)) {
if (this.bodyUsed) {
throw new DOMException(
`Body has already been used for "${this.url}".`,
DOMExceptionNameEnum.invalidStateError
);
}

const taskID = this.#asyncTaskManager.startTask(() => this.signal[PropertySymbol.abort]());
let formData: FormData;
(<boolean>this.bodyUsed) = true;

const taskID = this.#asyncTaskManager.startTask(() => this.signal[PropertySymbol.abort]());
let formData: FormData;

try {
const type = this[PropertySymbol.contentType];
formData = (await MultipartFormDataParser.streamToFormData(this.body, type)).formData;
} catch (error) {
this.#asyncTaskManager.endTask(taskID);
throw error;
}

try {
const type = this[PropertySymbol.contentType];
formData = (await MultipartFormDataParser.streamToFormData(this.body, type)).formData;
} catch (error) {
this.#asyncTaskManager.endTask(taskID);
throw error;

return formData;
}

this.#asyncTaskManager.endTask(taskID);
if (type && type.startsWith('application/x-www-form-urlencoded')) {
const parameters = new URLSearchParams(await this.text());

return formData;
const formData = new FormData();

for (const [key, value] of parameters) {
formData.append(key, value);
}

return formData;
}

throw new DOMException(
`Failed to build FormData object: The "content-type" header is neither "application/x-www-form-urlencoded" nor "multipart/form-data".`,
DOMExceptionNameEnum.invalidStateError
);
}

/**
Expand Down

0 comments on commit b447dc9

Please sign in to comment.