Created
November 4, 2013 04:06
-
-
Save liyu1981/7297938 to your computer and use it in GitHub Desktop.
simple nodejs http server print post body
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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