Trouble connecting Node app to Mlab (Error: URL malformed, cannot be parsed)

Trouble connecting Node app to Mlab (Error: URL malformed, cannot be parsed)

我的代码:

require('dotenv').config();

var mongoose = require('mongoose');
var gracefulShutdown;
var dbURI = 'mongodb://localhost/Loc8r';


if (process.env.NODE_ENV === 'production') {
    dbURI = process.env.MONGOLAB_URI;
}

mongoose.connect(dbURI);

在 运行 NODE_ENV=production nodemon 之后我得到了这个错误

(node:10624) UnhandledPromiseRejectionWarning: Error: URL malformed, cannot be parsed

如果我手动设置 dbURI,它工作得很好

dbURI = 'mongodb://<dbuser>:<dbpassword>@ds****.mlab.com:****/database' 

我遇到了同样的问题,不知道情况是否与您的相同,但基本上我有这个节点脚本,它通过 NodeJS 驱动程序(没有 Mongoose)连接到 MongoDB,我运行 此脚本通过 *NIX cron 作业。

无论如何,阅读 dotenv docs 我发现您实际上可以像这样解析配置结果:

const dotenv = require('dotenv')
const result = dotenv.config()
if (result.error) { throw result.error }
console.log(result.parsed)

我这样做了,结果我的脚本假设我的 .env 文件在用户的家中,而不是项目根目录(是的,我 运行 在 AWS EC2 上运行它)。错误很明显:

Error: ENOENT: no such file or directory, open '/home/ec2-user/.env'

所以,是的,确保你的 .env 文件可以从脚本执行目录中访问(在我的例子中,我从 /home/ec2-user 执行脚本,我的项目根目录是 /home/ec2-user/项目)。

TL;DR: 通过绝对路径指定 .env 位置,像这样

require('dotenv').config({path: '/full/custom/path/to/your/.env'})