【问题标题】:UnhandledPromiseRejectionWarning: Error: URI does not have hostname, domain name and tldUnhandledPromiseRejectionWarning:错误:URI 没有主机名、域名和 tld
【发布时间】:2020-05-24 18:50:26
【问题描述】:

我正在学习 Wes Bos 的教程,学习 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

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

【问题讨论】:

  • 你能确认console.log(process.env.DATABASE);输出正确的uri吗?
  • 是的,我回来了:mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster1-rgvum.mongodb.net/test?retryWrites=true 和我的 env 文件夹中的完全一样。

标签: javascript node.js mongodb mongoose


【解决方案1】:

是的,因为密码中使用了特殊字符,只要用这个简单的方法,或者使用上面的复杂代码进行编码。

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

所以像这样使用它:- pass123%23

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      试试这个:

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

      【讨论】:

        【解决方案4】:

        面临同样的问题。它不是 URL 编码的......

        快速解决方案 创建安全密码的最佳情况是使用 cloud.mongodb.com 中的“自动生成安全密码”功能来匹配要求。

        【讨论】:

          【解决方案5】:

          尝试添加引号:

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

          【讨论】:

            【解决方案6】:

            发生这种情况是因为您的密码不是 url 编码的。 Mongo 连接需要对密码进行 url 编码。只需尝试将 {useNewUrlParser: true} 添加到您的连接方法。见下文:

            mongoose.connect(keys.mongoURI, {useNewUrlParser: true}, (err, db) => {});
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-09-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-04-27
              • 2014-12-29
              相关资源
              最近更新 更多