Search This Blog

Tuesday, March 25, 2014

HOW TO: Write a Node.js service that accepts POST requests like a boss

I found it very difficult to create a service that can handle a post request sent from other applications in Node.js.
So, I took my laptop and started  searching..

I found all sort of tutorials that led me to things like:
// ?name=tobi
req.param('name')
// => "tobi"

// POST name=tobi
req.param('name')
// => "tobi"

// /user/tobi for /user/:name
req.param('name')
// => "tobi"
BUT IT DIDN'T WORK!

All i got was null, undefined and {}
And I wasn't alone!
stackoverflow is full with questions about this subject and each and every one of them have a different answer!

The obvious decision was to stay with expressjs or with connect and try to make them work.

Well, I found out that W3 provides two regulations for POST request encoding:
1. multipart/form-data
2. application/x-www-form-urlencoded
While application/x-www-form-urlencoded is the more common type of encoding and multipart/form-data is used mostly for uploading files.

And the tools i was using ware configured to the second one "application/x-www-form-urlencoded".

So how did I make it work?!
I've bundled myself this Node.js snippet:
(requires node-querystring)

var encoder = require('querystring');
app.post('/postman', function(req, res) {
var Body='';
req.on('data', function(chunk) {
Body += chunk.toString();
});

req.on('end', function() {
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
var decodedBody = encoder.parse(Body);
console.log(decodedBody.name);
console.log(decodedBody);
res.end();
});
});



Testing your service!
I like to use these two tools:
1. curl from Terminal
curl --data "name=value1" http://localhost:3000/Postman/
curl -XPOST http://localhost:3000/Postman -d 'name=val1'
2. Postman from Chrome Web browser


Accessing from your app!