javascript - UnhandledPromiseRejectionWarning 错误 :

我正在尝试在我的终端中运行 nodemon index.js,但我收到以下错误,我完全不知道这对我来说意味着什么非常不清楚。

谁能告诉我如何解决这个问题?

index.js

const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

var app = express();

var router = require('./services/router');

mongoose.connect('mongodb://localhost:apiAuth');

app.use(morgan('combined'));
app.use(bodyParser.json());
app.use('/v1', router);

var PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';

console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);

services/router.js

var router = require('express').Router();

function protected(req, res, next) {
    res.send('Here is the secret!');
}

router.route('/protected')
    .get(protected);

module.exports = router;

终端

[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Listening on 127.0.0.1 3000
(node:29104) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Slash in host identifier
(node:29104) [DEP0018] 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 连接到 MongoDB。


短版:

您输入了错误的登录 URL:

mongoose.connect('mongodb://localhost:apiAuth');
                                      ^^^^^^^

我想你想写(或类似的东西):

mongoose.connect('mongodb://localhost:'+apiAuth);

这是一个 MongoDB 登录 URL 的示例:mongodb://127.0.0.1:27017/my_db。 或文档:Standard Connection String Format


加长版:

问题的解决方法与上述相同,但您应该自己找到它。 就我而言,我是这样进行的(因为我遇到了完全相同的问题,但信息量也一样多)。

  1. 隔离产生错误的代码:您可以简单地对部分代码进行注释,以确定哪个区域发生了崩溃。
  2. 在与 Mongoose 连接后添加 catch():mongoose.connect(...).catch((e) => { console.log(e); throw e ; }。这将直接指示相关行和一些附加信息。

这种技术在很多情况下都有效。

关于javascript - UnhandledPromiseRejectionWarning 错误 : Slash in host identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49682075/

相关文章:

mongodb - 要将一条记录与 MongoDB 中的另一条记录相关联,可以使用 slug 吗?

mongodb - 使用 mongodb 聚合的多个字段的不同计数

json - 使用 Python 从 MongoDB 文档创建 JSON 文件

node.js - 如何在没有回调的情况下返回 Mongoose 查询结果

node.js - 我应该使用什么数据类型来使用 MongoDB 存储图像?

node.js - Mongoose 类型错误 : User is not a constructo

node.js - 使用 winston-mongodb 和 express-winston 进行日

c# - ReadBsonType 只能在 State 为 Type 时调用,不能在 State 为

java - Spring MongoTemplate - 将聚合结果映射到集合(例如 List 和

java - Mongo 将 Document 转换为 DBObject