当我想在 Heroku 上部署我的应用程序时,我有了一个奇怪的发现:当我使用“nodemon”启动服务器时,与数据库的连接工作正常。如果我使用“node server.js”,则不会建立与数据库的连接。我实际上认为这两个命令做同样的事情,除了感谢nodemon,你不必在每次更改后重新启动服务器。
有人知道这个问题以及如何解决它吗?非常感谢!
我的技术堆栈:Angular 14.3、Node 20.11、Express 4.17.1、Mongoose 8.2.3
这是错误:
Connection to database failed! MongoServerError: bad auth : authentication failed
at Connection.sendCommand (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connection.js:281:27)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Connection.command (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connection.js:304:26)
at async continueScramConversation (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\auth\scram.js:131:15)
at async executeScram (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\auth\scram.js:80:5)
at async performInitialHandshake (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connect.js:101:13)
at async connect (C:\Users\torbe\Documents\my-music-theory\backend\node_modules\mongodb\lib\cmap\connect.js:19:9) {
errorResponse: {
ok: 0,
errmsg: 'bad auth : authentication failed',
code: 8000,
codeName: 'AtlasError'
},
ok: 0,
code: 8000,
codeName: 'AtlasError',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}
这是我的package.json:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"engines": {
"node": "20.x"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "Torben Jan Müller",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^8.2.3",
"mongoose-unique-validator": "^5.0.0",
"nodemon": "^2.0.12",
"request-ip": "^3.3.0"
},
"devDependencies": {
"@types/request-ip": "0.0.38"
}
}
问题是由server.js文件中的环境变量引起的。它存储在nodemon.js 文件中,因此当使用“node server.js”启动服务器时无法找到它。环境变量现在存储在 .env 文件中,数据库已连接并且部署到 Heroku 也可以完美运行。
安装dotenv
npm i dotenv
服务器.js
require('dotenv').config();
const connectToDataBase = async () => {
try {
await mongoose.connect("mongodb+srv://<username:" + process.env.MONGO_ATLAS_PW + "@<cluster>.mongodb.net/<collection>?retryWrites=true&w=majority");
console.log('Connected to database!');
} catch (err) {
console.log('Connection to database failed!', err);
}
}
connectToDataBase();
在根目录中创建一个 .env 文件并包含环境变量
MONGO_ATLAS_PW = "password"