Skip to content

Instantly share code, notes, and snippets.

@liyu1981
Created November 4, 2013 04:06
Show Gist options
  • Save liyu1981/7297938 to your computer and use it in GitHub Desktop.
Save liyu1981/7297938 to your computer and use it in GitHub Desktop.
simple nodejs http server print post body
var http = require('http');
var querystring = require('querystring');
function processPost(request, response, callback) {
var queryData = "";
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
if(queryData.length > 1e6) {
queryData = "";
response.writeHead(413, {'Content-Type': 'text/plain'}).end();
request.connection.destroy();
}
});
request.on('end', function() {
response.post = querystring.parse(queryData);
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
http.createServer(function(request, response) {
if(request.method == 'POST') {
processPost(request, response, function() {
console.log(response.post);
// Use response.post here
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
});
} else {
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
}
}).listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment