亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用數據庫進行 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 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號