尝试将我的 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");
});
});
确保连接字符串正确。验证用户名、密码、集群名称和数据库名称。
let connectionString =
"mongodb+srv://nithyananthankrishnan:<password>@cluster0.ooz4hi1.mongodb.net/ToDoist?retryWrites=true&w=majority&appName=Cluster0";
确保
<password>
占位符替换为实际密码,并且如果包含特殊字符,则进行 URL 编码。