1

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]

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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);
    });
});

3 Comments

appreciated, any way to do this without express ? I don't want to change app structure.
I am using 'querystring' module.
Unfortunately this solution doesn't address multi depth brackets (i.e. user[3][name])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.