How to parse form elements array in NodeJS ?
Like in PHP we get $_POST['answers'] for form elements with names: answers[0], answers[1], answer[2] .... answers[n]
I got my own solution for this, for example I am getting data in var obj:
console.log("\n\n\n\n\n\n\n\n\n");
var obj = {
'answer[\'test\']': 'first',
'answer[\'2\']': 'second'
};
var new_obj = {};
for(key in obj){
key.replace(/([^\[]+)\['([^\]]+)'\]/g, function($0, $1, $2){
new_obj[$1] = new_obj[$1] || {};
new_obj[$1][$2] = obj[key];
})
}
console.log(new_obj);
Check out formidable it can parse any form you give it. It's also the module that connect and express use to parse the form data.
Using the popular node.js framework Express, it is as simple as:
var express = require('express'),
app = express.createServer();
app.use(express.bodyParser());
app.post('/foo', function(req, res, next) {
// Echo the POST body
res.send(req.body);
});
app.listen(3000);
Testing with curl:
curl -d foo=1 -d foo=2 localhost:3000/foo
Similar to in PHP, req.body.foo will be an array with all the foos you posted.
Edit: The querystring module is indeed what Express uses internally. If you need to accept file uploads, use formidable as Jan Jongboom suggests. Otherwise, here's basically how you would do it with just node:
var http = require('http'),
qs = require('querystring');
var app = http.createServer(function(req, res) {
var buffer = '';
req.setEncoding('utf-8');
req.on('data', function(data) {
buffer += data;
});
req.on('end', function() {
var body = qs.parse(buffer);
});
});