当我尝试启动我的 Node.js 应用程序时出现 UnhandledPromiseRejectionWarning 错误

时间:2021-01-16 19:15:57

标签: node.js mongodb mongoose

我的代码:

const fastify = require('fastify');
const mongoose = require('mongoose');

const app = fastify();

try {
    mongoose.connect('mongodb://localhost:27017/notes_db');
} catch (e) {
    console.error(e);
}

app.get('/', (request, reply) => {
    try{
        reply.send("Olá mundo");
    } catch(e) {
        console.error(e);
    }
})

app.listen(5000, (err, address) => {
    if (err) {
        console.error(err);
        process.exit(1);
    }
    console.log(`Server running on ${address}`);
});

当我运行命令 npm startnode index.js 时,会向我显示此错误:

(node:10332) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Server running on http://127.0.0.1:5000
(node:10332) UnhandledPromiseRejectionWarning: Error: Password contains an illegal unescaped character
    at parseConnectionString (C:\Users\mikae\Desktop\notes-server\node_modules\mongodb\lib\url_parser.js:299:13)
    at parseHandler (C:\Users\mikae\Desktop\notes-server\node_modules\mongodb\lib\url_parser.js:130:14)
    at QueryReqWrap.callback (C:\Users\mikae\Desktop\notes-server\node_modules\mongodb\lib\url_parser.js:114:7)
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:205:10)
(node:10332) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10332) [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.

我的服务器正在运行,但我想知道如何修复此消息。

1 个答案:

答案 0 :(得分:1)

您可以尝试像这样指定 useNewUrlParser 选项吗:

try {
    mongoose.connect('mongodb://localhost:27017/notes_db', { useNewUrlParser: true });
} catch (e) {
    console.error(e);
}

编辑

由于您尝试连接到 MongoDB Atlas 集群而不是本地安装,请将连接 URI 替换为您在 Atlas 上获得的 URI。

这是我找到的教程:https://medium.com/@sergio13prez/connecting-to-mongodb-atlas-d1381f184369