【问题标题】:GET call with a database使用数据库进行 GET 调用
【发布时间】:2020-09-13 06:57:04
【问题描述】:

我想创建一个 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 上的终端/控制台中显示的数据相同的数据

我的代码有什么问题?

【问题讨论】:

  • 如消息所示,database 在您的 get 方法中未定义,您正尝试在未定义的内容上调用方法 .all。我在您的代码中没有看到您设置database 的值。它仅在 .open 上的 .then(...) 方法范围内定义。

标签: javascript node.js json sqlite express


【解决方案1】:

数据库将以异步方式初始化,所以你应该等到你有一个数据库实例,然后保存它。

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

const app = express()

let globalDatabase

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

  })

  app.get('/', (request, response) => {
    if(globalDatabase) {
      globalDatabase.all('SELECT * FROM cities').then(cities => {
        response.send(cities)
      })
    }else{
       // todo whatever you want send error, or wait for db or initialize it again
    }

  })

  app.listen(3000)

【讨论】:

  • 我想这样做,以便我的代码对 localhost 进行 POST 调用,这会在调用正文中添加一个城市(名称值和来自 JSON 对象的人口值)城市表。像这样:{ "name": "Test city", "population": 123 }我该怎么做?
  • 您需要添加一个新端点,例如app.post("/addCity",(req, res) => { // read req.body for incoming parameters and use your db to save it. })
【解决方案2】:

看起来您的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 端点之前解决,否则它们也会失败。希望这会有所帮助

【讨论】:

  • 这行得通,但我在尝试以下操作时遇到了困难:我想这样做,所以我的代码对 localhost 进行 POST 调用,这会添加一个城市(名称值和人口值来自在城市表中的调用正文中发送的 JSON 对象。像这样: { "name": "Test city", "population": 123 } 我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
相关资源
最近更新 更多