Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...