【问题标题】:nodejs api call is not respondingnodejs api调用没有响应
【发布时间】:2020-09-29 11:36:23
【问题描述】:

我是 JS 世界的新手,正在努力学习 NodeJs 基础知识,这就是我想要做的。

我的 mongoDb 中有一个联系人,编写一个 get 方法将其取回给调用者。简单吧?

这是我的路由器方法

import {
  getContact
} from '../controllers/crmController'
const routes = (app) => {
  app.route('/contact').get((req, res, next) => {
    console.log(`request URL ${req.originalUrl}`)
    console.log(`request method ${req.method}`)
    next()
  }, getContact)
}
export default routes

这是我的客户控制器代码

import {
  getDbContact
} from '../data-access/crmDataAccess'
export const getContact = (req, res) => {
  console.log(`Controller calling db access`)
  var dbContact = getDbContact()
  console.log(`Controller Recieved ${dbContact}`)
  res.json(dbContact)
}

这是我通过 mongoose 访问的数据

import mongoose from 'mongoose'
import { ContactSchema } from '../models/crmModel'
const Contact = mongoose.model('Contact', ContactSchema)
export const getDbContact = () => {
  Contact.find({}, (err, contact) => {
    if (err) {
      console.log(`Error ${err}`)
    } else {
      console.log(`Contact Recieved ${contact}`)
      return contact
    }
  })
}

从控制台日志中,我可以看到正在从数据库中获取数据,但它从未响应邮递员的呼叫。我想我在从控制器调用 db 访问方法时做错了什么.. 但很可疑,不知道是什么.. 有人可以帮帮我吗?谢谢

【问题讨论】:

  • (1) getDbContact 没有返回联系人,(2) getContact 没有正确处理承诺。
  • 谢谢,你能把可以实现相同功能的代码扔在这里吗?基本上我希望这三层依次返回到路由器..!

标签: javascript node.js express mongoose promise


【解决方案1】:
  1. 你需要await getDbContact()(因为它是异步的),否则代码执行将通过,联系人将始终未定义

  2. getDbContact 必须返回一个 Promise 才能等待它。 Mongoose 方法是 Promise,你可以直接返回它。

  3. 错误处理逻辑应该在控制器中,而不是在 DB 访问器中。

控制器:

export const getContact = async (req, res) => { // add "async" so you can use "await" inside

    console.log(`Controller calling db access`)

    try {

        let dbContact = await getDbContact(); // use "let" or "const"; "var" is old-school all-purpose ES5
        console.log(`Controller Recieved `, dbContact); // dbContact is not a string. Log it this way
        res.json(dbContact);

    } catch(err) {
        res.status(500).send(err);
    }
}

数据库访问器:

export const getDbContact = () => Contact.find({})
                 .lean() // returns simple JSON, faster
                 .exec() // non-blocking

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多