How to parse POST data in node.js?

Some JavaScript libraries send data by POST instead of JSON. In node.js, how to parse the POST data?

asked Oct 15, 2015 by anonymous

1 Answer

You can use the "querystring" module:

var qs = require('querystring')

The following piece of code works well for me. The comments should help you read the code well.

var post_handle = function(request, response) {
    if (request.method == 'POST') {
        // save all data received
        var postdata = '';
    
        // receiving data
        request.on('data', function(chunk) {
            postdata += chunk;                                                                 
            // Avoid too much POST data                                                        
            if (postdata.length > 1e6)
                request.connection.destroy();
        });

        // received all data
        request.on('end', function() {
            var post = qs.parse(postdata);
            // handle post by accessing
            // post['name']
            // response.send(process(post['name']));
        });
    } else {
        console.log("Non POST request received at " + request.url);
    }
}
answered Oct 15, 2015 by Eric Z Ma (44,280 points)
How to send POST request in JavaScript? asked Oct 15, 2015 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Related questions

1 answer
1 answer
asked Oct 15, 2015 by Eric Z Ma (44,280 points)
1 answer
asked Oct 20, 2014 by Eric Z Ma (44,280 points)
1 answer
2 answers
1 answer
0 answers
Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...