Pointing a domain to my remote Node JS application?

淺唱寂寞╮ 提交于 2019-12-02 16:51:33

You need to separate the notion of the domain name from the actual server. The domain name points to a server. When the browser (or other client) asks for example.com, DNS looks up the associated IP address and directs the browser to the server at that IP address.

The browser then chooses which port to send its request through by looking at the URL. For example, a request for example.com:345 will select port 345. If left unspecified, by default, when using HTTP, it uses port 80.

So the browser has sent its request through port 80. Now, on your server, there is a program listening to that port. For you, it would nginx. Nginx reads the request ("oh, you're looking for index.html") and delivers back the contents you requested.

In your scenario, Node.JS replaces Nginx. For Node.JS to respond, it would also need to listen to a port and respond appropriately. That's where your code comes in:

require('http').createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, "127.0.0.1");

This starts a server, listening at port 1337. Any requests directed to example.com:1337 would be responded to by this Node.JS application with a "Hello World".

tl;dr: Your domain name already points to your server. You can access your application at example.com:1337, where 1337 is your port.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!