【发布时间】: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