I have an assignment to write an http
server in node.js
, which is why I can't use the http
module, as you'll soon see. Anyway, I need to be able to listen to both GET and POST requests. The way I understand it GET only fires data
event, and post fires data
and end
. Here's my code:
function Server(resourceMap, rootFolder) {
this.resourceMap = resourceMap;
this.rootFolder = rootFolder;
function connectionHandler(socket) {
console.log('server connected');
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.setEncoding('utf8');
socket.on('data',function(data) {
var re = new RegExp("^( *)(GET)", "i");
if (data.match(re) != null) {
console.log("Handling GET request");
router.route(data,socket,handle,resourceMap,rootFolder);
}
else {
(function() {
var postData = data;
socket.on('data',function(data) {
postData += data;
});
console.log(postData);
socket.on('end',function(postData) {
console.log("END");
console.log("Handling POST request");
router.route(postData,socket,handle,resourceMap,rootFolder);
});
});
}
});
}
this.server = net.createServer(connectionHandler);
this.port = undefined;
this.startServer = function(port) { //Maybe change backlog for security reasons
this.port = port;
this.server.listen(port, function() { //'listening' listener add handle object here
console.log('server bound');});
}
}
GET
requests works just fine. With POST
It doesn't even enter the anonymous function.
Any ideas why and how I can solve it?
EDIT: solved - I defined the function but didn't call it :) If you have any comments about my design I'd love to hear, as I am new to node.js and JavaSCript
Thanks