javascript - 使用数据库进行 GET 调用
问题描述
我想创建一个 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
当您在承诺中使用它但未分配它时,看起来您的即将出现未定义。您可以通过以下方式解决您的问题:
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 端点之前解决,否则它们也会失败。希望这可以帮助
推荐阅读
- python - 仅从 pandas 数据框列中的 json 格式获取特定键值
- react-native - 无需电话号码即可与 Twilio Flex 和 React Native 聊天
- c# - HTTP 未解析的 ping - TCP 服务器
- firebase - 从 firebase 存储读取并使用 firebase 函数写入 firestore
- python - 将嵌套字典转换为数据框
- linux - find -perm 查找不存在的文件(或其他文件)
- ajax - 我跟着一个视频教程。我正在尝试使用 ajax 和 jquery 在我的 django 项目的主页上呈现微调器
- c# - 蛇盒属性的类属性
- docker - 使用策略“”拉取图像失败:图像拉取失败:后退拉取图像“
" - google-apps-script - 使用 Google Ads 脚本在电子表格列中搜索值