How to parse POST data in node.js?

Posted on In QA

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

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

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *