【问题标题】:As a client, what port am I supposed to connect to when running a MongoDB server that is connected to a NodeJS app?作为客户端,当运行连接到 NodeJS 应用程序的 MongoDB 服务器时,我应该连接到哪个端口?
【发布时间】:2021-12-14 19:13:22
【问题描述】:

我的本​​地网络上有两个端口在服务器上运行:27017 是 MongoDB 的端口,3000 是我的 nodejs 应用程序的端口。然后我在监听端口 3000 时使用 mongoose connect 连接两者。

var db = mongoose.connect('mongodb://localhost/test')

app.listen(3000, () => {
   console.log('listening on port 3000')
})

以前我试图通过网络浏览器使用 http://(server ip):27017 连接到服务器,但我在 NodeJS 应用程序中编写的 GET 永远不会被调用。

app.get('/', (req, res) => {
   res.send('hello world')
})

我将端口切换到 3000,http://(server ip):3000,最后我得到了 GET 的响应。

那么客户端应该如何连接到他们的服务器?通过他们的nodejs应用程序而不是数据库?当使用 TLS 和 HTTP 时,客户端是否也应该连接到 nodejs 应用程序?

【问题讨论】:

    标签: node.js mongodb rest client-server


    【解决方案1】:

    浏览器客户端应该连接到您的网络服务器,而不是数据库,所以在 你上面的例子,那将在端口 3000 上。

    那么客户端应该如何连接到他们的服务器?通过他们的 nodejs 应用程序而不是数据库?

    是的。数据库是供您的服务器使用的,而不是供客户端直接使用的。任何客户端与数据库的交互都是通过您的服务器间接发生的。

    当使用 TLS 和 HTTP 时,客户端是否也应该连接到 nodejs 应用程序?

    如果服务器在本地运行,仅使用 localhost 访问它,那么可能不需要 https。

    现在一般建议在 https 上运行 public 服务器。这意味着您将从像 Let's Encrypt 这样的证书颁发机构获得证书,并在 Let's Encrypt 网站的这个示例中使用带有 https 凭据选项的 https.createServer()

    // Dependencies
    const fs = require('fs');
    const https = require('https');
    const express = require('express');
    
    const app = express();
    
    // Certificate
    const privateKey = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8');
    const certificate = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/cert.pem', 'utf8');
    const ca = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/chain.pem', 'utf8');
    
    const credentials = {
        key: privateKey,
        cert: certificate,
        ca: ca
    };
    
    app.use((req, res) => {
        res.send('Hello there !');
    });
    
    // Starting https server
    const httpsServer = https.createServer(credentials, app);
    
    httpsServer.listen(443, () => {
        console.log('HTTPS Server running on port 443');
    });
    

    注意,您通常会在端口 443 上运行 https 服务器。然后,您将使用 https 协议而不是 http 连接到此服务器。如果您使用 443(https 的默认端口号),则无需在浏览器 URL 中指定端口,但如果不使用端口 443,则需要指定端口。

    【讨论】:

    • 对不起,我应该更清楚“当使用带有 HTTP 的 TLS 时,客户端还应该连接到 nodejs 应用程序吗?”,我的意思是:客户端也应该连接到 nodejs 应用程序,而不是数据库,当客户端尝试使用带有 HTTP (https) 的 TLS 连接时?
    • @pgs1 - 我仍然不确定你在问什么关于 TLS 的问题。据我所知,HTTP 没有 TLS。根据定义,使用 http 协议的 TLS 是 HTTPS。它是一个 HTTPS 服务器,其中实现了 TLS 以供客户端连接。现在大部分可能只是语义,因为 HTTP 协议 + TLS 是 HTTPS。在浏览器中,您告诉浏览器使用 TLS 的方式是通过以 https:// 开头的 URL(以指定 https 协议)。
    • 是的,我的意思是 HTTPS,因为我刚开始学习它,所以我很困惑。我还查看了您正在谈论的证书,我认为我能够通过使用指令 here 在服务器和客户端之间创建 https 连接来生成适当的证书和密钥。感谢您的帮助!
    猜你喜欢
    • 2012-12-05
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多