node.jswebserverlocaltunnel

How to send http(s) requests with Node.js to a Node.js server hosted with LocalTunnel


I have a very basic node.js server:

var http = require("http");

var server = http.createServer(function(req, res){
    console.log("Got request");

    res.writeHead(200, {"Content-Type":"text/plain"});
    res.end("Hi there!");
});

server.listen(3004);

I can access this via my browser and via sending a request from a Node.js client:

var http = require("http");

var options = {
    "hostname": "localhost",
    "port": 3004,
    "path": "/",
    "method": "GET"
};

var req = http.request(options, function(res){
    var data = "";

    res.on("data", function(chunk){
        data += chunk;
    });

    res.on("end", function(){
        console.log(data);
    });
});

req.on("error", function(e){
    console.log(e.stack);
});

req.end();

Now if I use the localtunnel package to "host" this server ( lt --port 3004 ), I now get my new hostname that I should be able to access it from on the internet. And indeed, I can easily access it from the browser.

However, if I try to send an https (not http because lt uses https) request from the Node.js client, with the new hostname, the request is refused and I get this error:

Error: connect ECONNREFUSED 138.197.63.247:3004 at TCPConnectWrap.afterConnect [as oncomplete]

So is it not possible to access a node.js web server when it is hosted with localtunnel? Or if there is (maybe using a 3rd part module) can someone please guide me on how that would be done as google is of absolutely no help. Thanks in advance.

EDIT1: I should note that on the server side, the error message does suggest "checking my firewall, but I have no idea what in my firewall could be blocking this, I'm not sure what to do. (Remember that this works when connecting from the browser??)

EDIT2: BTW, I tried to completely remove my firewall (got same result)


Solution

  • The issue is that you are not sending your request with the right port. When you use a tunneling service like localtunnel, it hosts your server as HTTPS. Now usually the port used for HTTPS is port 443, so the options object should look something like this:

    var options = {
        "hostname": "whatever",
        "port": 443,  //HERE!
        "path": "/",
        "method": "GET"
    };
    

    The same goes for services like zeit or heroku that host your app from their cloud.