Last active
April 22, 2022 19:42
-
-
Save justinnoel/a06ed34c05f8742b7fac1a17e1f1be0b to your computer and use it in GitHub Desktop.
A Cloudflare Worker to extract POST data submitted as either JSON or as a form.
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
addEventListener("fetch", (event) => { | |
event.respondWith(handleRequest(event.request).catch((err) => new Response(err.stack, {status: 500}))); | |
}); | |
async function handleRequest(request) { | |
const {pathname} = new URL(request.url); | |
if (pathname.startsWith("/api/post")) { | |
const {data, error} = await getPostData(request); | |
if (error) { | |
return new Response(error, {status: 400}) | |
} | |
return new Response(JSON.stringify(data), { | |
headers: { | |
"Content-Type": "application/json" | |
}, | |
status: 200 | |
}); | |
} | |
return new Response("Not found", {status: 404}); | |
} | |
async function getPostData(request) { | |
const response = { | |
data: null, | |
error: null | |
} | |
try { | |
const {headers} = request; | |
const contentType = headers.get("content-type") || ""; | |
if (contentType.includes("application/json")) { | |
response.data = await request.json(); | |
return response; | |
} | |
if (contentType.includes("form")) { | |
const formData = await request.formData(); | |
const body = {}; | |
for (const entry of formData.entries()) { | |
body[entry[0]] = entry[1]; | |
} | |
response.data = body | |
return response; | |
} | |
response.error = "Content-type must be application/json, application/x-www-form-urlencoded, or multipart/form-data" | |
return response; | |
} catch (e) { | |
console.log(`ERROR: getPostData -> exception -> ${ | |
e.message | |
}`); | |
response.error = "request failed"; | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment