简体   繁体   中英

Why does connecting to different port result different error Node.js

a little background, I am self learning Node.js and I created a hello.js file on my mac and ran it using node hello.js . I can access the webpage page fine from either localhost:port or 127.0.0.1:port .

My ultimate goal is to be able to access the web page from other machines. I looked through many SO pages. I added '0.0.0.0' in my app.listen() but still not successful so far, I am sure I will figure out later. I know there are many question and duplicates about how to connect to localhost from other machines devices, please don't get confused because that is NOT my question!

In my process of figuring out how to do so, I got curious of why when I try to connect to different port I get different errors from chrome from my other machine?

This is my hello.js:

const http = require('http'); 

http.createServer((request, response) => {

    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    response.write('Hello, My name is Oliver\n');
    response.end();

}).listen(1337, '0.0.0.0', function() {
    console.log('Listening to port:  ' + 1337);
});

port 1337: When I use port 1337 by running node hello.js 在此处输入图片说明

I can connect to the page fine on my mac using 127.0.0.1:1337 . But when I try to connect it from my other machine (Windows) using Chrome I get

在此处输入图片说明

port 2701 Now when I use port 2701 again running node hello.js 在此处输入图片说明 again trying to connect it from my other machine using 127.0.0.1:2701 I get the following error from chrome: 在此处输入图片说明

port 1433 following the above steps then I get this error:

在此处输入图片说明

I didn't change the code at all but I when I switch different port I get different error. There are some posts about connecting to differnt ports with Node.js for example: HTTPComponent Connect to different port or Node js route request to different port

But these posts didn't touch on why it result in different errors. Can someone please explain this behavior?

EDIT: I realize that 127.0.0.1 refers to my localhost so I would have to use my real IP address of my Mac. However my curiosity remains, why does connecting to different ports on localhost result in different errors?

When you want to access your server from another machine, you should use its real IP adress. 127.0.0.1 or localhost is for local use only.

Eg your Mac has IP 123.456.789.123. By local call you can use 127.0.0.1, localhost or 123.456.789.123. For remote call you have always to use 123.456.789.123.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM