如何在Node.js中访问MariaDB查询结果?

n3h0vuf2  于 2022-11-08  发布在  Node.js
关注(0)|答案(1)|浏览(161)

我最近开始自学使用Node.js创建网站,我需要从mariaDB中检索SELECT查询,以便最终使用此数据作为JSON响应,响应客户端浏览器上网页的POST请求。我搜索了Web和stackoverflow,但没有找到任何相关解决方案。
我已经创建了Node/Express代码,它成功地检索了数据库查询并将其记录到服务器控制台-但我无法成功地将查询结果发送回客户端。我遗漏了什么/做错了什么?
这是服务器端代码:-
(the get_publishers和accessDB函数的代码完全基于“MariaDB连接器/节点. js(Promise API)示例”中的示例)

const express = require('express')
const mariadb = require('mariadb')

// get list of publishers
function get_publishers(conn) {
    return conn.query("SELECT * FROM publishers")
}

// get database SELECT query
async function accessDB() {
    let conn
    let queryResult
    try {
        conn = await mariadb.createConnection({
            host: "localhost",
            user: "****",
            password: "****",
            database: "*****"
        })
        queryResult = await get_publishers(conn)
        console.log('db query complete')
    }  catch (err) {
        console.log(err) 
    } finally {
       console.log(queryResult)
        if (conn)  conn.end()
        console.log('db connection closed')
        return queryResult
    }
}

const app = express()
app.use(express.static(__dirname + '/public'))

const http = require('http');
const fs = require('fs');
const port = process.env.PORT || 3000;

app.get('/listPublishers', (req, res) => {
    res.type('text/plain')
    const now = new Date()
   res.send( now + ' query result = ' + JSON.stringify(accessDB()))
//   res.send(accessDB())
})

app.listen(port, () => console.log(
    'bookStore 16:26 started with accessDB on http://localhost:${port}; ' +
    'press Ctrl-C to terminate.....'))

这是控制台日志的输出。它显示查询结果符合预期。

$ node bookstore.js
bookStore 16:26 started with accessDB on http://localhost:${port}; press Ctrl-C to terminate.....
db query complete
[
  { publisherID: 1, publisherName: 'Jonathon Cape' },
  { publisherID: 2, publisherName: 'W. W. Norton & Co' },
  { publisherID: 3, publisherName: 'Corgi Books' },
  ...
  { publisherID: 10, publisherName: 'Gollanz' },
  { publisherID: 11, publisherName: 'Continuum' },
  meta: [
    ColumnDef {
      collation: [Collation],
  ...
      type: 'SHORT'
    },
    ColumnDef {
      collation: [Collation],
  ...
      type: 'BLOB'
    }
  ]
]
db connection closed

..这是客户端浏览器上的结果

Mon Oct 03 2022 15:15:14 GMT+0100 (British Summer Time) query result = {}

......除非我误解了,它似乎是个空的物体。

vmdwslir

vmdwslir1#

您的accessDB()调用是一个异步函数,您需要在res.send()完成 * 之后 * 调用它:

accessDB().then(data => res.send(new Date() + ' query result = ' + JSON.stringify(data)))

相关问题