首页 > 解决方案 > 从节点中的数据库返回多行

问题描述

我正在尝试返回产品的所有详细信息并以表格格式显示它们

我已经在我的 api 中尝试过这个

app.get('/test',(req,res) => {
const client = new Client({
    connectionString: connectionString
})
client.connect()
client.query('select * from product',(err,res) =>{
    console.log(err,res)
    if(err){
        console.log(err);
    }else{
        console.log(res);


    }
    client.end()
})})

我如何在节点中返回这个资源?

标签: javascriptnode.js

解决方案


您正在使用查询结果的内部资源将外部资源隐藏在路由处理程序中。

我必须对您的查询客户端做出一些假设,但如果内部 res 是行数组,只需将其传递给 res.json() 函数(另一个假设是您使用的是 Express)。

我的建议:

app.get('/test', (req, res) => {
    const client = new Client({
        connectionString: connectionString
    })
    client.connect()
    client.query('select * from product', (err, rows) => {
        console.log(err, rows)
        if (err) {
            console.log(err);
        } else {
            console.log(rows);

            res.json(rows);

        }
        client.end()
    })
});

推荐阅读