我想创建一个NodeJS程序来从数据库提供JSON-ray。我正在使用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
看起来好像不确定,因为您在诺言中使用它但未分配它。您可以通过以下方式解决您的问题:
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端点之前解决,否则它们也会失败。希望对您有所帮助