0

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

4

1 に答える 1

1

よくある間違い:関数を定義したが、呼び出さなかった。

次のいずれかを実行できます。

正規表現のfunctionキーワードを後で削除します

または()、関数の後に追加します(これはより推奨されます)

于 2012-12-10T08:08:11.890 に答える