How to access form body in oak/deno

拈花ヽ惹草 提交于 2021-01-28 21:34:32

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/62363699/how-to-access-form-body-in-oak-deno

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!