Ruben Ruben - 1 month ago 15
Node.js Question

Can't connect to nodejs on ubuntu xenial

I am using vagrant to create a machine on virtualbox. The machine only has a fresh install of Ubuntu (updated) and node.

node server.js works find with the installation in my system. Can see the "Hello world" on chrome.
But when I ssh into my machine and use node server.js on the server, I get ERR_CONNECTION_RESET on chrome.

Here is all my code

Vagrantfile:

Vagrant.require_version ">= 1.8.6"

Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"

config.vm.network "forwarded_port", guest: 3000, host: 3000
config.vm.synced_folder ".", "/var/www/", :mount_options => ["dmode=777", "fmode=666"]

config.vm.provider "virtualbox" do |virtualbox|
virtualbox.name = "vagrant"
virtualbox.memory = 512
virtualbox.cpus = 1
virtualbox.gui = false
end
end


server.js

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});


software versions:


  • windows 10 Home

  • vagrant 1.8.6

  • virtualbox 5.1.8

  • ubuntu xenial 64

  • node v6.9.1


Answer

When running inside Vagrant, the address 127.0.0.1 does not necessarily map to 'localhost'. Remove the hostname and you should be fine:

server.listen(port, () => {
  console.log(`Server listening ${port}/`);
});

Omitting the hostname defaults to 0.0.0.0

Comments