Plain Text Body Parsing with Express on NodeJs

After playing around with Express on NodeJs for a little while now, I noticed one peculiarity in how body parsing is done.  If I do an http POST in my front end code like so:

$.ajax({
    url: "/postStuffHere",  
    contentType: "text/plain",
    type: "POST",
    processData: false,
    data: $("#inputField").val(),
    success: function (data) {
        console.log("success!");
        console.dir(data);
    }
});

Then when I receive the POST on the backend with the following code:

app.post("/postStuffHere", function (req, res, next) {
    console.log("received a POST!");
    console.dir(req.body);
});

I see the following output:

received a POST!
undefined

After some digging, I found that Express uses the Connect middleware framework, and that the behavior I was looking for was within the bodyParser of Connect. A relevant snippet from the bodyParser documentation:

By default application/json, application/x-www-form-urlencoded, and multipart/form-data are supported, however you may map connect.bodyParser.parse[contentType] to a function receiving (req, options, callback).

So with this in mind, I looked up the source code for bodyParser’s included JSON parsing, and crafted the following:

app.configure(function () {
        express.bodyParser.parse["text/plain"] = function (req, options, fn) {
        var buf = "";
        req.setEncoding("utf8");
        req.on("data", function (chunk) {
            buf += chunk;
        });

        req.on("end", function () {
            try {
                req.body = buf;
                fn();
            } catch (err) {
                fn(err);
            }
        });
    };
     app.use(express.bodyParser());
});

The above is very similar to the JSON parsing routine that Connect comes with. You can now accept POSTs with a contentType of “text/plain”, and the req.body will simply contain the body of the request.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>