The code registers two callbacks - one for the 'data' event which is called when a chunk of body data arrives (there may be more than one such call depending on the size of the body) and the other for the 'end' event when the request has "ended".
Of course, this example is too simple to use in most real systems (caveat lector) - no checks on the content are made, and the parsing takes place only after the whole body is read. Not ideal.
var http = require('http');
var url = require('url') ;
http.createServer(
function (request, response) {
var full_url = url.parse( request.url, true ) ;
var pathname = full_url.pathname ;
var q_params = full_url.query ;
var body = "" ;
response.writeHead(200, {'Content-Type': 'text/plain'});
if ( request.method === "POST" &&
request.headers['content-type'] === "application/x-www-form-urlencoded"){
request.on('data', function( chunk ) {// append the chunk to the growing message body
body += chunk ;
}) ;
request.on('end', function(){
var params = body.split('&') ;
for ( param in params ){
var pair = params[param].split('=') ;
response.write("Name: " + pair[0] + " = " + pair[1] + "\n") ;
}
response.end() ;
}) ;
}
}
).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
3 comments:
Awesome, thank you for posting this. I was searching for about an hour for a good example and finally found yours. It works great!
Awesome, thank you for posting this. I spent about an hour looking for a good example and finally found yours.
I do have a quick question though... using your code and a simple form I created, when I post data from a text field it displays as "Hello+World!" instead of just "Hello World!".
Can you explain why the + is included in every spacing and perhaps how I could get rid of it?
Thanks!
@tehskylark:
You get the '+' because the form is URL-encoded. In order to change the '+' back to a ' ' you would need to url-decode the form data.
Post a Comment