How to access form body in oak/deno

Viewed 2950

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("/");
});
2 Answers

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("/");
});

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'
}
Related