Search code examples
koa

how to extract form fields with koa


I am having trouble extracting form fields in koa:

Say I send a form like this:

<form action="/somewhere" method="post">
  <input type="text" name="somefield"/>
</form> 

How can I extract these on the backend:

  router.post('/somewhere', async ctx => {
    const { form } = ctx.req; //not here

  });

Solution

  • You'll need to use some middleware to parse the request body. Check out koa-bodyparser. You can use it like so:

    app.js

    const Koa = require('koa')
    const bodyParser = require('koa-bodyparser')
    const router = require('./routes')
    
    const app = new Koa()
    
    app.use(bodyParser()) // Make sure you `use` bodyParser before your router
    app.use(router.routes())
    app.use(router.allowedMethods())
    

    routes.js

    const Router = require('koa-router')
    
    const router = new Router()
    
    router.post('/somewhere', async ctx => {
      console.log(ctx.request.body.somefield); // All your form fields will be available on the `ctx.request.body` object
    })