Last active
November 12, 2021 11:46
-
-
Save justinnoel/8f576c9c274d36f69fb4b2e85ffbbe3c to your computer and use it in GitHub Desktop.
Extract Form Submission Details for a Cloudflare Worker.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.