使用数据库进行 GET 调用

我想创建一个NodeJS程序,从数据库中提供JSON-aray。我正在使用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:3000TypeError: Cannot read property 'all' of undefined


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


我的代码出了什么问题?


阿晨1998
浏览 174回答 2
2回答

鸿蒙传说

数据库将以异步方式初始化,因此您应该等到有数据库实例,然后保存它。const express = require('express')const sqlite = require('sqlite')const sqlite3 = require('sqlite3')const app = express()let globalDatabasesqlite  .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)

心有法竹

看起来你的出现是未定义的,因为你在承诺中使用它,但没有分配它。您可以通过以下方式解决问题:databaselet databasesqlite  .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 终结点之前解决,否则它们也会失败。希望这有帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript