Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Hostname not working node.js

Hostname not working node.js

Problem

My code is as follows:

    var http = require('http');
    var static = require('node-static');
    var file = new static.Server();

    http.createServer(function (req, res) {
            file.serve(req, res);
    }).listen(1337, '127.0.0.1');

When the url is localhost:1337/1.html it works fine. However if I change it to hostname:1337/ where 'hostname' is the hostname of my server, I get unable to establish connection error. In PHP i could easily replace 127.0.0.1 or localhost with hostname. Why isn't the same possible in node.js?

Problem courtesy of: Manas Jayanth

Solution

So the problem is when your browser resolves "hostname", DNS gives it your local network IP address like 192.168.0.42, but your code tells node to listen on one and only one IP address: 127.0.0.1, so the connection doesn't work. Replace '127.0.0.1' in your node code with '0.0.0.0' (which means "all IP addresses") and things will work. Be advised that other computers on your local network (like other folks in a coffee shop wifi network) will be able to connect to your application, which is why for development sticking with the loopback IP address (127.0.0.1) and 'localhost' are better choices.

Solution courtesy of: Peter Lyons

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Hostname not working node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×