Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 33172  / 9 Years ago, tue, november 17, 2015, 12:00:00

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.


More From » koa

 Answers
33

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

[#64378] Friday, November 13, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lamontm

Total Points: 482
Total Questions: 99
Total Answers: 91

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;