为了账号安全,请及时绑定邮箱和手机立即绑定

使用数据库进行 GET 调用

使用数据库进行 GET 调用

阿晨1998 2022-09-02 16:26:54
我想创建一个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 databasesqlite  .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我的代码出了什么问题?
查看完整描述

2 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

数据库将以异步方式初始化,因此您应该等到有数据库实例,然后保存它。


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)


查看完整回答
反对 回复 2022-09-02
?
心有法竹

TA贡献1866条经验 获得超5个赞

看起来你的出现是未定义的,因为你在承诺中使用它,但没有分配它。您可以通过以下方式解决问题: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 终结点之前解决,否则它们也会失败。希望这有帮助


查看完整回答
反对 回复 2022-09-02
  • 2 回答
  • 0 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号