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?

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

Similar Posts

Leave a Reply

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