首页 > 解决方案 > 使用数据库进行 GET 调用

问题描述

我想创建一个 NodeJS 程序,它从数据库中提供 JSON 数组。我正在使用 express、sqlite 和 sqlite3 包。当我在终端中运行代码时,我得到以下输出:

$ node index.js
[
  { Field1: 'Stockholm', Field2: '123' },
  { Field1: 'Gothenburg', Field2: '123' },
  { Field1: 'London', Field2: '123' }
]

它显示正确的数据。

这是我的代码:

const express = require('express')
const sqlite = require('sqlite')
const sqlite3 = require('sqlite3')

const app = express()

let database

sqlite
  .open({ driver: sqlite3.Database, filename: 'test.sqlite' })
  .then((database) => {
    database.all('SELECT * FROM cities').then(rows => {
        console.log(rows)      
      })
  })

  app.get('/', (request, response) => {
    database.all('SELECT * FROM cities').then(cities => {
      response.send(cities)
    })
  })

  app.listen(3000)

当我运行上面的代码时,http://localhost:3000我收到一条错误消息:TypeError: Cannot read property 'all' of undefined

我想显示与终端/控制台中显示的数据相同的数据http://localhost:3000

我的代码有什么问题?

标签: javascriptnode.jsjsonsqliteexpress

解决方案


database当您在承诺中使用它但未分配它时,看起来您的即将出现未定义。您可以通过以下方式解决您的问题:

let database

sqlite
  .open({ driver: sqlite3.Database, filename: 'test.sqlite' })
  .then((db) => {
    // assign it here
    database = db;
    database.all('SELECT * FROM cities').then(rows => {
       console.log(rows)      
    })
  })

然后,您以后就可以使用它了。请记住,这个承诺需要在请求到达您的 GET 端点之前解决,否则它们也会失败。希望这可以帮助


推荐阅读