Search code examples
javascriptkoabody-parser

How to parse multipart/form-data body with Koa?


Because I spent some (too much) time figuring out this simple requirement. I am documenting here the way to achieve multipart/form-data body parsing with Koa.

In my case, the reason of the confusion was the number of alternatives available out there:

And I wanted to find the most minimalist/close to express/koa/node way/philosophy of doing things.

So here it is. Below. In accepted answer. Hope this helps.


Solution

  • You have to use koa-multer as stated in the official Koa wiki.

    So a simple setup would look like:

    const koa = require('koa');
    const multer = require('koa-multer');
    
    const app = koa();
    
    app.use(multer());
    
    app.use(function *() {
      this.body = this.req.body;
    });
    

    A couple of notes:

    • Multer will only parse bodies of requests of type multipart/form-data
    • Notice the use of this.req.body instead of Koa's supercharged this.request (not sure if this is intentional but this is confusing for sure... I would expect the parsed body to be available on this.request...)

    And sending this HTML form as FormData:

    <form>
      <input type="hidden" name="topsecret" value="1">
      <input type="text" name="area51[lat]" value="37.235065">
      <input type="text" name="area51[lng]" value="-115.811117">
      ...
    </form>
    

    Would give you access to nested properties as expected:

    // -> console.log(this.req.body)
    {
      "topsecret": 1,
      "area51": {
        "lat": "37.235065",
        "lng": "-115.811117",
      }
    }