我试图隐藏我的连接字符串,所以我在项目中安装了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变量时,加ahuthentiation失败,如何正确连接一个变量?这是我的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);
})
答案 0 :(得分:0)
好像您正在使用Node和Heroku。在这种情况下,
例如,如果您创建名为“ MONGO_URI”的Heroku配置变量,请在您的节点应用程序中将其称为process.env.MONGO_URI。
详细信息可以在这里找到:https://devcenter.heroku.com/articles/config-vars#managing-config-vars