Parsing form data with node.js
Posted on 24/11/09 by Felix Geisendörfer
Many people asked about form parsing in #node.js after the initial buzz-wave yesterday.
Right now node does not include a parser for regular form data (application/x-www-form-urlencoded). However, you can use the http multipart parser to achieve the same thing.
Here is a bare-bone example for that:
var multipart = require('multipart');
var sys = require('sys');
var server = http.createServer(function(req, res) {
switch (req.uri.path) {
case '/':
res.sendHeader(200, {'Content-Type': 'text/html'});
res.sendBody(
'<form action="/myaction" method="post" enctype="multipart/form-data">'+
'<input type="text" name="field1">'+
'<input type="text" name="field2">'+
'<input type="submit" value="Submit">'+
'</form>'
);
res.finish();
break;
case '/myaction':
multipart.parse(req).addCallback(function(parts) {
res.sendHeader(200, {'Content-Type': 'text/plain'});
res.sendBody(sys.inspect(parts));
res.finish();
});
break;
}
});
server.listen(8000);
Run this code and point your browser to http://localhost:8000/. You will be presented with a form, and when you submit it, you will see the contents of the POST as JSON. For more information check:
The important part is specifying the enctype of your form as "multipart/form-data".
If you need to parse regular form data, have a look at sixtus www-forms module. Chances are good a module like this, with a similar API to the multipart parser, will make it into the core at some point (patches are welcome).
HTH,
-- Felix Geisendörfer aka the_undefined
You can skip to the end and add a comment.
I got an error code in pointing my browser to http://localhost:8000/.
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.
Sweet!
Except you don't look at the HTTP verbs at all.
People copy code examples, always show example code you would like to find in a code audit.