Skip to content

Instantly share code, notes, and snippets.

@FrankGrimm
Created November 7, 2010 22:08
Show Gist options
  • Save FrankGrimm/666908 to your computer and use it in GitHub Desktop.
Save FrankGrimm/666908 to your computer and use it in GitHub Desktop.
Basic example on how to get the body data of a HTTP request in node.js
var http = require('http');
var querystring = require('querystring');
var utils = require('utils');
http.createServer(function (req, res) {
switch(req.url) {
case '/':
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.write('<html><head><title>Example</title></head><body>');
res.write('<form enctype="application/x-www-form-urlencoded" action="/formhandler" method="post">');
res.write('<input type="text" name="foobar" value="foobar" />');
res.write('<input type="text" name="barfoo" value="123" />');
res.write('<input type="submit" />');
res.write('</form></body></html');
res.end();
break;
case '/formhandler':
if (req.method == 'POST') {
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
req.on('data', function(chunk) {
// body data is received
// for productive use this chunk of data might have to be
// buffered and processed in the end-event
res.write(utils.inspect(querystring.parse(chunk)));
});
req.on('end', function() {
// no more body data -> end response
res.end();
});
} else {
res.writeHead(405, "Method not supported", {'Content-Type': 'text/html'});
res.end();
}
break;
default:
res.writeHead(404, "Not found", {'Content-Type': 'text/html'});
res.end('<html><head><title>404 - Not found</title></head><body><h1>Not found.</h1></body></html>');
console.log("[404] " + req.url);
};
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment