How do you extract POST form data and file uploads in node.js?

 

laptop_shutterstock_119563954

One of the most common tasks in creating a Node web server is handling GET and POST calls.  GET calls are fairly straightforward, however POST calls are more involved.  POST form data and POST file uploads provide the ability for a web client to upload enormous amounts of data to your server.  Proper safeguards must be put into place to insure that your server does not crash if it runs out of resources required to handle a POST of unlimited size.

Many of the common Node frameworks, like Express, provide an abstraction layer that allows you to more easily access POST data.  However, if you are rolling your own web server in Node, you will need to handle this with your own code.  The example below will allow you to do so.

var http = require('http');
var querystring = require('querystring');

function receivePost(request, response, callback) {
    var queryData = "";
    if(typeof callback !== 'function') return null;
    request.on('data', function(data) {
         queryData += data;
         if(queryData.length > 6e6) { // limit uploaded data to 6M
             queryData = "";
             response.writeHead(413, {'Content-Type': 'text/plain'}).end();
              // Kill connection if over 6M of data received
             request.connection.destroy();
         }
     });

    request.on('end', function() {
        // Parse the final result and save as request.post
        request.post = querystring.parse(queryData);
        callback();
    });
}

http.createServer(function(request, response) {
    if(request.method == 'POST') {
        receivePost(request, response, function() {
            console.log(request.post);
            
            // This section is where you would process the result of receivePost

            response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
            response.end();
        });
    } else {
        response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
        response.end();
    }

}).listen(3000);

Wherever you are handling POST requests, just simply pass the request and response fields to receivePost.  This function will collect the incoming data, and it to a working variable, and insure that it does not exceed 6MB of data (easily changed if you want to allow more or less).  When it returns, request.post will contain the POST data object that you can then manipulate and process as required.

Tagged on: , ,

Leave a Reply

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