我的本地主机拒绝连接,对于我用于将 mongodb 连接到节点应用程序的简单应用程序

问题描述 投票:0回答:1

尝试将我的 Node 应用程序连接到 MongoDB 时,终端中没有出现错误。但是,localhost:3000 拒绝连接。我已验证服务器正在运行并侦听正确的端口。 MongoDB Atlas 中的 IP 白名单设置为 0.0.0.0/0。尽管进行了这些检查,连接问题仍然存在。我使用了netstat -ano | findstr :3000 检查端口是否正在监听,结果显示该端口未被使用。此外,终端不会显示“服务器正在 http://localhost:3000 上运行”。当我使用命令curl http://localhost:3000时,它显示curl: (7) Failed to connect to localhost port 3000 after 2251 ms: Couldn't connect to server.

let express = require("express");
let mongodb = require("mongodb");

let app = express();

let db;
let MongoClient = mongodb.MongoClient;
let connectionString =
  "mongodb+srv://nithyananthankrishnan:<password>@cluster0.ooz4hi1.mongodb.net/ToDoist?retryWrites=true&w=majority&appName=Cluster0";

MongoClient.connect(
  connectionString,

  function (err, client) {
    if (err) {
      console.error("Failed to connect to the database:", err.message);
      return;
    }
    db = client.db();
    console.log("Database connected successfully.");
    app.listen(3000, () => {
      console.log("Server is running on http://localhost:3000");
    });
  }
);
app.use(express.urlencoded({ extended: false }));

app.get("/", function (req, res) {
  res.send('hello world');
});

app.post("/create-item", function (req, res) {
  db.collection("items").insertOne({ text: req.body.item }, function () {
    res.send("thanks for submitting the form");
  });
});

  1. 我尝试了不同的端口号,例如 3001
  2. 尝试关闭防火墙 但没有什么对我有用
javascript node.js express mongodb-atlas mongodb-atlas-search
1个回答
0
投票

确保连接字符串正确。验证用户名、密码、集群名称和数据库名称。

let connectionString =
      "mongodb+srv://nithyananthankrishnan:<password>@cluster0.ooz4hi1.mongodb.net/ToDoist?retryWrites=true&w=majority&appName=Cluster0";

确保

<password>
占位符替换为实际密码,并且如果包含特殊字符,则进行 URL 编码。

© www.soinside.com 2019 - 2024. All rights reserved.