【发布时间】: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