Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
791 views
Welcome To Ask or Share your Answers For Others

1 Answer

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",
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...