UnhandledPromiseRejectionWarning:错误:URI没有主机名,域名和tld

问题描述 投票:0回答:3

我正在按照Wes Bos,Learn Node.js的教程学习。

我下载了所有的起始文件并使用MongoDb Atlas创建了一个数据库。

当我运行npm start时出现此错误:

UnhandledPromiseRejectionWarning: Error: URI does not have hostname, domain name and tld
DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我正在使用环境变量来连接数据库

mongoose.connect(process.env.DATABASE);

变量看起来像这样:

DATABASE=mongodb+srv://<username>:<password>@cluster1-rgvum.mongodb.net/test?retryWrites=true

出于显而易见的原因,我省略了用户名和密码如果有人知道如何继续,将不胜感激!谢谢。

javascript node.js mongodb mongoose
3个回答
1
投票

确保您的用户名和密码不包含特殊字符。它会打破解析。

这是导致我遇到同样错误的原因。


1
投票

是的,因为在密码中使用特殊字符,只需使用这种简单的方法使用上述复杂的编码代码。

在密码中使用十六进制代码而不是您在密码中使用的符号,如果您在文本中的密码是: - pass123#

所以使用它像: - pass123%23

从这里获取ASCII代码并使用十六进制代码: - https://ascii.cl/

有关更多详细信息: - https://docs.atlas.mongodb.com/troubleshoot-connection/#special-characters-in-connection-string-password


0
投票

尝试添加引号:

DATABASE="mongodb+srv://<username>:<password>@cluster1-rgvum.mongodb.net/test?retryWrites=true"

0
投票

它与URI中的特殊字符(可能是您的密码)有关。

试试这个:

"mongodb+srv://<username>:" + encodeURIComponent(<password>) + "@cluster1-rgvum.mongodb.net/test?retryWrites=true"

0
投票

发生这种情况是因为您的密码未经过网址编码。 Mongo连接要求密码为url编码。只需尝试将{useNewUrlParser:true}添加到您的connect方法中。见下文:

mongoose.connect(keys.mongoURI, {useNewUrlParser: true}, (err, db) => {});
© www.soinside.com 2019 - 2024. All rights reserved.