【问题标题】:How to listen on my public IP address port using Nodejs如何使用 Nodejs 监听我的公共 IP 地址端口
【发布时间】:2019-08-16 01:57:47
【问题描述】:

我希望使用我的公共 IP 地址而不是本地主机来访问我的 Nodejs 应用程序。现在为了在本地主机上托管我的应用程序,我正在做:

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

我想设置 Nodejs 到 Nodejs 的通信。我从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);
});

但是,我想使用公共 IP 地址,因为我想在 Heroku 上托管我的一台服务器。我将需要公共 IP 地址来创建通信

【问题讨论】:

  • 到目前为止,您在部署应用程序方面做了哪些尝试?您是否有服务器设置和访问权限?是否要将应用程序 docker 化?

标签: node.js heroku


【解决方案1】:

如何让你的 node.js 监听你的公共 IP

实际上,您的 nodejs 服务器侦听 port 9000,这意味着该端口上的任何通信都将被侦听。您唯一需要的是打开此端口以允许来自“外部”的请求。

对于heroku,我认为你不能这样做。但是,根据文档,端口 80 和 443 已经打开,所以如果您将端口更改为其中之一,它会起作用!

奖金:

如何打开端口(在 Linux 上)

您可以使用 ufw,一个简单而著名的防火墙管理器。

sudo ufw allow 9000

此命令将打开您的端口 9000 并允许外部请求重新请求您的 nodejs 服务器

我建议你之前阅读ufw的文档,看看这个很好的tutorial

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多