【问题标题】:nodeJS UnhandledPromiseRejectionWarning: errornodeJS UnhandledPromiseRejectionWarning:错误
【发布时间】:2018-08-23 11:00:27
【问题描述】:

我完全不知道发生了什么。这是我第一次尝试自己开发全栈 mern 应用程序,当我尝试研究这个问题时,我大部分时间都不理解代码/解释。

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

app.use(bodyParser.json())
app.use(morgan('dev'))


mongoose.connect('mongodb://localhost/gundamstore' ,{ useNewUrlParser: true 
}, (err) => {
if (err) throw err
console.log('connected to the database')
})

// -------------------Don't forget to connect routes here-------------

app.listen(9000, () => {
    console.log('this server is running on port 9000')
})

我也收到 body-parser is deprecated 错误,但是当我放入 { useNewUrlParser: true } 行时,该错误就消失了。我以前从来没有遇到过这个错误,也不知道我为什么会这样。

如果有人可以告诉我我正在做什么来解决这个问题?

【问题讨论】:

  • 在使用 promise 时最好使用 then() 调用成功, catch() 调用失败,因为 mongoose.connect() 返回一个 promise。
  • 由于 express >= 4.16.0 body-parser 现在是 express 的一部分,所以你可以说app.use(express.json())
  • @AsafAviv 我还需要顶部的 const bodyParser 吗?
  • 不,你没有,你应该从你的package.json文件中删除它。

标签: node.js express server


【解决方案1】:

试试这个,

mongoose.connect(uri, options).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
  err => { /** handle initial connection error */ }
);

【讨论】:

    【解决方案2】:

    我发现我没有正确配置 mongoDB。我需要进入我的系统文件并将 PATH 设置为 mongoDB bin 目录。关于 Promise,我还有很多东西要学,但我很高兴我弄明白了。

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2022-01-08
      • 1970-01-01
      • 2018-02-23
      • 2021-11-17
      • 2019-11-02
      相关资源
      最近更新 更多