【问题标题】:Connection to MongoDB server using Node is unresponsive on localhost使用 Node 连接到 MongoDB 服务器在 localhost 上无响应
【发布时间】:2019-09-22 20:15:38
【问题描述】:

我正在尝试将我的 node.js 游戏连接到 MongoDB 集群,以便我可以存储用户名和密码。我已经使用 express + socket.io 在本地存储了一个模拟数据库。我正在尝试设置 MongoDB 地图集来存储用户名 + 密码,这样当本地主机关闭时,数据就不会消失。

我已经逐字尝试了以下Developing A RESTful API With Node.js And MongoDB Atlas。当我测试我的连接是否成功时,我在终端上输入:

node app.js

我的服务器按预期启动并打印server started。在本教程中,我应该会看到错误或成功的连接消息。但是,当我启动服务器时,我也看不到。我在调试时遇到了麻烦,因为我根本没有得到任何响应。

这是我的 app.js 文件的开头上下文。

// Express code
var express = require('express');
var app = express();
var serv = require('http').Server(app); 
var MongoClient = require('mongodb').MongoClient;


const CONNECTION_URL = *uri here* 
const DATABASE_NAME = "bunnyCrossing";

var timeRemaining; 
// If query is '/' (nothing)
app.get('/',function(req,res){
    res.sendFile(__dirname + '/client/index.html');
});

// If query is '/client'. Client can only request things from client folder
app.use('/client',express.static(__dirname + '/client')); 

// replace the uri string with your connection string.
var database, collection;

app.listen(3000, () => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
        if(error) {
            throw error;
        }
        database = client.db(DATABASE_NAME);
        collection = database.collection("people");
        console.log("Connected to `" + DATABASE_NAME + "`!");
    });
});
// Server starts listening on port 2000
serv.listen(2000);
console.log("Server started");

我应该在运行 node app.js 时看到:

server started
Connected to `bunnyCrossing`!

但我只是看到:

server started

【问题讨论】:

  • 你确定你的服务器监听成功了吗? console.logserv.listen 之后不要确保您的服务器正在运行,尝试将console.log("Server started"); 移动到app.listen 的回调。尝试将端口 200 更改为其他端口。
  • @Hongarc 当我修复控制台日志并转到 localhost 2000 时,服务器启动并打印正确的消息。当我将端口 3000 更改为端口 2000 时,会引发服务器错误““错误:监听 EADDRINUSE :::2000”。我知道这意味着端口 2000 正在使用中,所以我只是对 Mongo 应该在哪个端口上感到困惑。
  • 你只运行serv.listenapp.listen,不要同时运行。 app.listen 并不意味着您为MongoClient 选择端口您不需要多一个端口来运行MongoClient,MongoDb 服务器会这样做,并且您将端口配置为在CONNECTION_URL 中连接

标签: node.js mongodb express socket.io


【解决方案1】:

app.listen 没有被调用,或者您必须点击localhost:3000 来调用回调以连接到 mongo 数据库。

删除serv.listen 或向serv.listen 添加回调并删除app.listen

serv.listen(2000, function(err) {
  if (err) console.log(err);
  else {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
        if(error) {
            throw error;
        }
        database = client.db(DATABASE_NAME);
        collection = database.collection("people");
        console.log("Connected to `" + DATABASE_NAME + "`!");
    });
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2021-12-30
    • 2015-07-05
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多