how do I access post data in a deno http server?
Hi y'all,
I am perfectly aware that it may be my limited knowledge on the JS eco system, but I have not found a warking way to access POSTed data in a deno http Server.
What do I have to do here?
// example Server
async function handler(req: Request): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;
const method = req.method;
let module;
console.log( req)
if ("GET" === method) {
return new Response("Hello", { status: 200 })
}
if ("POST" === method) {
// What do I have to do here, to get the data?
// I've tried: readAll
// const buf = await req.body();
// const buf = await readAll(req.body);
// const json = JSON.parse(decoder.decode(buf));
// const decoder = new TextDecoder();
// decoder.decode( req.body)
// const body = await req.formData()
return new Response("Hello, where's my data?", { status: 200 })
}
return new Response("Method not implemented", { status: 501 });
}
Deno.serve(handler);
// Following is an example curl call:
curl -d "param1=value1¶m2=value2" -X POST http://localhost:8000/test
Thank you for your time and help.
Inke
7 Replies
if ("POST" === method) {
const body = JSON.parse(await req.text());
console.log(body);
return new Response("Hello, where's my data?", { status: 200 })
}
try this
For URL encoded post data (like your curl call seems to be), I use this:
For raw json:
For multipart post:
...and for detecting which one to use:
Thank you veodium, req.text() works.
And thank you ranioroo, this would probably have been my next stumbling block.
Why is this so hard to find? (Well guess, it's common knowledge for everyone else 🙂
Well, I remember all this was surprisingly hard/painful to figure out, since there are so many different ways to POST, and all needed to be handled in a different way, wasn't that obvious :)
read examples in the official document
and more and more googling 🙂
I know, google is my friend, but it turned out to be a fickly friend and was giving me pre 2.0 answers which I didn't get to work.