【发布时间】:2020-04-08 02:10:57
【问题描述】:
我试图隐藏我的连接字符串,所以我在我的项目中安装了 env2。然后我制作了一个 config.env 文件来保存我的连接字符串,如下所示:
export DB_URL='mongodb://user:userPassword@ds241968.mlab.com:41968/heroku_hc9xjmcl'
但是,当我将该变量用作连接字符串时,我无法连接到 Mlab,我收到以下错误:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [ds241968.mlab.com:41968] on first connect [MongoError: Authentication failed.]
但是,当我尝试仅连接字符串而不使用 env2 时,我可以完美连接,那么为什么当我使用 env 变量时验证失败以及如何正确连接呢?这是我的 server.js:
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3009;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
const env = require('env2')('../config.env');
console.log(process.env.DB_URL)
app.use(cors());
app.use(bodyParser.json());
const { DB_URL } = process.env;
mongoose.connect( DB_URL , { useNewUrlParser: true } )
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Connection to MongoDB established succesfully!');
});
// Serve static assets
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
itemRoutes.route('/').get( async (req, res) => {
let collection = connection.collection("posts");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/comments').get( async (req, res) => {
let collection = connection.collection("comments");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/userComments')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
let comment = new Comment(req.body);
comment.save()
.then(comment => {
res.status(200).json({comment})
})
.catch(err => {
res.status(400).send('failed')
})
});
app.use('/', itemRoutes);
app.use('/userComments', itemRoutes);
app.listen(PORT, function() {
console.log('Server is running on' + ' ' + PORT);
})
【问题讨论】:
-
当您尝试
console.log(DB_URL);时会得到什么? -
尝试删除连接字符串周围的引号
-
@MEDZ 我得到的连接 url 与变量中的完全一样
-
@Intellidroid 如果我删除字符串,我会收到此错误:
cdconnection is not defined -
您实际上是否也在 Heroku 上托管您的应用程序?如果你是的话,也许可以在那里使用他们的环境变量?
标签: node.js mongodb heroku mongoose mlab