【问题标题】:NodeJS does not return JSON but gets the data from dbNodeJS 不返回 JSON 而是从 db 获取数据
【发布时间】:2020-09-23 19:51:41
【问题描述】:

我有一个应用程序需要从我的数据库中提取数据..

当我尝试这个时:

// get all customers
router.get('/customers', (req, res, next)  => {
  let userList = []
  // async/await - check out a client
  ;(async () => {
    const client = await pool.connect()
    try {
      const res = await client.query('SELECT id_user, username FROM users')
      userList = res.rows
      console.log(userList)
    } finally {
      // Make sure to release the client before any error handling,
      // just in case the error handling itself throws an error.
      client.release()
    }
  })().catch(err => console.log(err.stack))
  res.json("Hello there")
})

在前端调用 /api/v1/customers 时我得到了

// 20200923123622
// http://localhost:8008/api/v1/customers

"Hello there"

但在控制台中我可以正确看到结果:

[
  { id_user: 1, username: 'admin' },
  { id_user: 2, username: 'owner' }
]

但是当我尝试将 userList 作为 JSON 返回时

...
res.json(userList)
...

它最终在客户端作为一个永无止境的加载窗口(虽然我仍然可以在控制台中看到结果 - 正确的)

我错过了什么?

编辑: 得到了这个工作 - 非常感谢@kavigan

router.get('/customers', (req, res, next)  => {
  let userList
    (async () => {
      const res = await pool.query('SELECT id_user, username FROM users')
      userList = res.rows
    })().then((data) => {
        res.json(userList)
    }).catch(err => console.log(err.stack))

})

【问题讨论】:

  • res 不再是 Express 响应对象,而是您从数据库中返回的任何内容...
  • 除了上面@jonrsharpe 所说的之外,使用启用no-shadow 规则的ESLint 可以帮助您防止将来出现此类错误。

标签: javascript node.js postgresql api


【解决方案1】:

您搞砸了异步调用,因此需要更正代码,您可以这样做:

您需要使用 then() 并从那里返回响应,因为 IIFE 异步函数返回一个承诺并确保您返回它,在上面的代码中您没有返回它。

// get all customers
router.get('/customers', (req, res, next) => {
    let userList = []
        // async/await - check out a client
        (async () => {
            //your code
        })().then((data) => {
            res.json("Hello there");
        }).catch(err => console.log(err.stack));
});

或者像下面这样正确处理异步等待:

// get all customers
router.get('/customers', async (req, res, next) => {
    let userList = []
    // async/await - check out a client
    try {
        userList = await (async () => {
            //your code
        })();
    } catch (err) {
        console.log(err.stack)
    }
    res.json("Hello there");
});

【讨论】:

猜你喜欢
  • 2020-11-25
  • 1970-01-01
  • 2020-05-21
  • 2017-06-18
  • 1970-01-01
  • 2020-04-11
  • 2019-03-24
  • 2019-12-06
  • 1970-01-01
相关资源
最近更新 更多