Different between 127.0.0.1 and 0.0.0.0 with Node.js Demo Code

tanut aran
CODEMONDAY
Published in
Jul 16, 2023

127.0.0.1 only accept from that machine

Now we got node on the server and try to write sample code without any dependencies.

// server.js
const http = require('http')

const server = http.createServer((req,res) => {
res.statusCode = 200;
res.end('working');
})

server.listen(8000, '127.0.0.1', () => { console.log('started') })

Then you can run and background this Node.js job and try to access it from console.

$ node server.js

Hit Ctrl-Z

$ bg %1

Now the job is on the background

$ curl localhost:8000

Working !

But if you open the firewall and try to access from the browser

… It’s not working

0.0.0.0 accept from all interface

Now we change the ip from 127.0.0.1 to 0.0.0.0

server.listen(8000, '0.0.0.0', () => { console.log('started') })

Then go back to your browser and it’s working !

--

--