【发布时间】: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.log在serv.listen之后不要确保您的服务器正在运行,尝试将console.log("Server started");移动到app.listen的回调。尝试将端口 200 更改为其他端口。 -
@Hongarc 当我修复控制台日志并转到 localhost 2000 时,服务器启动并打印正确的消息。当我将端口 3000 更改为端口 2000 时,会引发服务器错误““错误:监听 EADDRINUSE :::2000”。我知道这意味着端口 2000 正在使用中,所以我只是对 Mongo 应该在哪个端口上感到困惑。
-
你只运行
serv.listen或app.listen,不要同时运行。app.listen并不意味着您为MongoClient选择端口您不需要多一个端口来运行MongoClient,MongoDb 服务器会这样做,并且您将端口配置为在CONNECTION_URL中连接
标签: node.js mongodb express socket.io