Skip to content

Instantly share code, notes, and snippets.

@justinnoel
Last active November 12, 2021 11:46
Show Gist options
  • Save justinnoel/8f576c9c274d36f69fb4b2e85ffbbe3c to your computer and use it in GitHub Desktop.
Save justinnoel/8f576c9c274d36f69fb4b2e85ffbbe3c to your computer and use it in GitHub Desktop.
Extract Form Submission Details for a Cloudflare Worker.
async function getFormData(request) {
const { headers } = request;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return await request.json();
}
if (contentType.includes("form")) {
const formData = await request.formData();
const body = {};
for (const entry of formData.entries()) {
body[entry[0]] = entry[1];
}
return body;
}
return null;
}
@justinnoel
Copy link
Author

justinnoel commented Nov 12, 2021

This supports the form being submitted the old fashion way by the browser or being handled by JavaScript and submitted as JSON.

In each case, the data is returned to the caller in JSON format.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment