Search code examples
javascriptnode.jsproxyjsonpscript-tag

Why does this nodejs proxy server hang?


In browser javascript is pathetically broken in that the only way to make requests is using script tags and jsonp. To make this useful, I'm trying to make a nodejs server that, given a callback name and address, loads the page at the address and pads it in a call to callback and serves the result. However, I know next to nothing about nodejs. If the server's response is loaded from a script tag it would result in actually loading a web page. Currently, I'm writing the request as localhost:8000/callback/address so a script tag might be <script src="localhost:8000/alert/https://www.google.com" type="text/javascript"></script>. Here is my code for the server:

var http = require("http");
var request = require("request");
var server = http.createServer(function(req, res){
    req.on("end", function(){
        console.log("alive");
        var url = req.url;
        var i = url.indexOf("/", 1);
        request(url.substring(i + 1), function(err, ret, body){
            res.writeHead(200);
            res.write(url.substring(1, i) + "(\"" + body + "\");");
            res.end();
        });
    });
});

server.listen(8000);

Why does this stay loading for a very long time but never actually load? By using console.log() it seems as if the req.on("end") callback is never even called.


Solution

  • If you don't care about any request data, you could just add req.resume(); after you add your end event handler.

    The reason it's getting "stuck" is that since node v0.10, streams start out in a paused state, so you need to unpause them by reading from them in some way. req.resume(); accomplishes this. Once there is nothing left in the request stream (which there could be nothing), the end event will be emitted.