Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top