简体   繁体   English

如何使用Node.js监听我的公共IP地址端口

[英]How to listen on my public IP address port using Nodejs

I want my Nodejs app to be accessed using my public IP address rather than the localhost. 我希望使用公共IP地址而不是本地主机访问Nodejs应用程序。 Right now for hosting my application on localhost I am doing: 现在要在本地主机上托管我的应用程序:

app.listen(process.env.PORT||9000,()=>{
    console.log('Server is running on 9000!')
})

I wanted to setup Nodejs to Nodejs communication. 我想设置Nodejs与Nodejs的通信。 I got help from stackoverflow and used the npm request package to send a post request from one of my nodejs server running on port 3000 to the one running on port 9000 我从stackoverflow获得了帮助,并使用npm request包将发布请求从运行在端口3000上的一台nodejs服务器发送到运行在端口9000上的一台发布服务器

const request = require("request");

var options = {
    method: 'POST',
    url: 'http://localhost:9000/',
    headers: { 'Content-Type': 'application/json' },
    body: { id: 1 },
    json: true
};

request(options, function (error, response, body) {
    if (error) throw new Error(error);

    // console.log(body);
    // Process the body and return the response.
    // return res.send(body);
});

I however want to use a public IP address because I want to host one of my server on Heroku. 但是,我想使用公共IP地址,因为我想在Heroku上托管我的一台服务器。 I will need the public IP address to create a communication 我将需要公共IP地址来创建通信

How to make your node.js listening on you public IP : 如何使您的node.js监听您的公共IP

Actually your nodejs server listen on port 9000 , wich mean any communication on this port will be listen. 实际上,您的nodejs服务器在port 9000上侦听,这意味着该端口上的所有通信都将被侦听。 THe only thing you need is to open this port to allow request from "outside". 您唯一需要做的就是打开此端口,以允许来自“外部”的请求。

For heroku , I don't think you can do this. 对于heroku ,我认为您不能这样做。 But, according to the documentation, port 80 and 443 are already open , so if you change your port to one of these it would work! 但是,根据文档, 端口80和443已经打开 ,因此,如果将端口更改为其中之一,则可以使用!

Bonus : 奖励:

How to open a port (on Linux) 如何打开端口(在Linux上)

You can use ufw, an easy and famous firewall manager. 您可以使用ufw,一个简单而著名的防火墙管理器。

sudo ufw allow 9000

This command will open your port 9000 and allow external request to resquest your nodejs server 此命令将打开您的端口9000,并允许外部请求重新请求您的nodejs服务器

I recommend you to read the doc of ufw before, and see this good tutorial 我建议您先阅读ufw的文档,然后阅读此好教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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