Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - How to parse multipart form data without frameworks?

I'm trying to do a basic thing: to send a form using FormData API and parse it in NodeJS.

After searching SO for an hour only to find answers using ExpressJS and other frameworks I think it deserves its own question:

I have this HTML:

<form action="http://foobar/message" method="POST">
  <label for="message">Message to send:</label>
  <input type="text" id="message" name="message">
  <button>Send message</button>
</form>

JS:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://foobar/message');
xhr.send(new FormData(form));

In NodeJS I'm doing:

var qs = require('querystring');

var requestBody = '';
request.on('data', function (chunk) {
  requestBody += chunk;
});
request.on('end', function () {
  var data = qs.parse(requestBody);
  console.log(data.message);
});

But in data.message I get the Webkit Boundary thing (from the multipart form data format) instead of the expected message. Is there another built-in lib to parse multipart post data instead of querystring? If not then how to do it manually (high-level, without reading the source code of Express)?

like image 232
krulik Avatar asked Nov 13 '16 16:11

krulik


1 Answers

I encounter the same problem; because the webserver I am using is written in C++ with a Javascript API (which is not the same as Node.js, although standard compliant). So I have to make my own wheel.

Then I come across this npm module parse-multipart-data. It works, and you can read the source code, it's just one file, and the author explain very clearly what it is, and how to do it.

P.S. as you go higher - you need to go lower. Experience programmer will know what I mean :)

like image 190
Joel Chu Avatar answered Nov 14 '22 00:11

Joel Chu