【发布时间】:2020-04-07 17:05:45
【问题描述】:
我正在尝试使用 config.env 文件中的 env 变量连接到我的 MongoDB 数据库,这样我的连接字符串就不会对所有人可见,但我不断收到我的 DB_URL is not defined 的错误,为什么?我该怎么做?我安装了env2,然后我创建了我的confing.env,它看起来像这样:
export DB_URL='mongodb://admin:username@password/heroku_url';
然后我在我的服务器 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 || 3001;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
require('env2')('../config.env')
app.use(cors());
app.use(bodyParser.json());
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);
})
【问题讨论】:
标签: node.js mongodb environment-variables