node js read fetch post body form data

Solutions on MaxInterview for node js read fetch post body form data by the best coders in the world

showing results for - "node js read fetch post body form data"
Francisco
23 Nov 2019
1/**
2 * Helper function for POSTing data as JSON with fetch.
3 *
4 * @param {Object} options
5 * @param {string} options.url - URL to POST data to
6 * @param {FormData} options.formData - `FormData` instance
7 * @return {Object} - Response body from URL that was POSTed to
8 */
9async function postFormDataAsJson({ url, formData }) {
10	const plainFormData = Object.fromEntries(formData.entries());
11	const formDataJsonString = JSON.stringify(plainFormData);
12
13	const fetchOptions = {
14		method: "POST",
15		headers: {
16			"Content-Type": "application/json",
17			Accept: "application/json",
18		},
19		body: formDataJsonString,
20	};
21
22	const response = await fetch(url, fetchOptions);
23
24	if (!response.ok) {
25		const errorMessage = await response.text();
26		throw new Error(errorMessage);
27	}
28
29	return response.json();
30}
31
32/**
33 * Event handler for a form submit event.
34 *
35 * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
36 *
37 * @param {SubmitEvent} event
38 */
39async function handleFormSubmit(event) {
40	event.preventDefault();
41
42	const form = event.currentTarget;
43	const url = form.action;
44
45	try {
46		const formData = new FormData(form);
47		const responseData = await postFormDataAsJson({ url, formData });
48
49		console.log({ responseData });
50	} catch (error) {
51		console.error(error);
52	}
53}
54
55const exampleForm = document.getElementById("example-form");
56exampleForm.addEventListener("submit", handleFormSubmit);