如何在 oak/deno 中访问表单正文

How to access form body in oak/deno

我正在使用 oak/deno。我有一个从提供的 ejs 文件提交的表单。如何访问表单主体?当我将它登录到控制台时,它会打印:{type: "form", value: URLSearchParamsImpl {} }

post 处理程序如下所示:

router.post("/add", async (ctx: RouterContext) => {
  const body = (await ctx.request.body())
  console.log(body)
  ctx.response.redirect("/");
});

如果您要发送 x-www-form-urlencoded,只需使用 body.value 中可用的 URLSearchParams 实例。

body.value.get('yourFieldName')

如果 body.type === "form-data" 您可以使用 .value.read(),您将获得 multipart/form-data 个字段

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

类似这样的东西 returns 值

看起来 body.value 是通过 .get(<key>) 访问的,或者可以使用 .entries()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'
}