3

I'm using oak/deno. I have a form that is submitted from an ejs file served up. How do I access the form body? When I log it to the console, it prints: {type: "form", value: URLSearchParamsImpl {} }

The post handler is shown below:

router.post("/add", async (ctx: RouterContext) => {
  const body = (await ctx.request.body())
  console.log(body)
  ctx.response.redirect("/");
});
jps
  • 20,041
  • 15
  • 75
  • 79
ishaangupte
  • 248
  • 2
  • 11

2 Answers2

6

If you're sending x-www-form-urlencoded just use URLSearchParams instance available in body.value.

body.value.get('yourFieldName')

If body.type === "form-data" you can use .value.read() and you'll get the multipart/form-data fields

router.post("/add", async (ctx: RouterContext) => {
  const body = await ctx.request.body({ type: 'form-data '});
  const formData = await body.value.read();
  console.log(formData.fields);
  ctx.response.redirect("/");
});
jps
  • 20,041
  • 15
  • 75
  • 79
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • This works correctly and allows access to the form data however the example mentions `multipart/form` data. How can the files be accessed? – Mark Tyers Feb 17 '21 at 12:37
4

something like this returns the values

it looked like body.value is accessed through .get(<key>) or can be iterated with .entries() or Object.fromEntries()

async register(context: RouterContext) {
  const body = context.request.body({ type: 'form' })
  const value = await body.value

  console.log(value.get('email'))

  for (const [key, val] of value.entries()) {
    console.log(key, val)
  }

  const args = Object.fromEntries(value)
  console.log(args)

  context.response.body = 'test'
}
jps
  • 20,041
  • 15
  • 75
  • 79
Don
  • 71
  • 1
  • 4
  • 1
    Please [edit] your answer to include an explanation of how this works and why it is of solution to the problem described in the question. See [answer]. – Gander Dec 15 '20 at 19:43
  • 1
    Thanks, that worked out fine! I'm using json body, so my code was a bit different: ```const body = ctx.request.body({ type: 'json' }); const parsedBody = await body.value; ``` – Marco Antônio Jul 12 '21 at 12:14