node.js - Express 应用程序无法从我的数据库中获取某些项目(Sqlite)
问题描述
我正在创建一个应用程序,用户可以在其中创建帖子并对此发表评论。创建、更新和删除帖子按预期工作,创建评论也是如此。
当用户创建评论时,其 accountId 被传递到数据库。
删除特定评论时,会传递 accountId 以验证是否允许用户删除它。
问题是,似乎没有从数据库中获取 accountId,尽管查询要求从名为“comments”的数据库表中获取所有详细信息。
该应用程序分为两个文件,db.js 和 app.js。
我已经尝试修改请求。为了排除故障,我添加了一行代码检查是否获取了 comment.accountId,但这就是我得到错误的地方。
/* in db.js: */
//get comment by comment id
exports.getCommentById = (id, callback) => {
const query = 'SELECT * FROM comments WHERE id = ?'
const values = [ id ]
db.all(query, values, (error, comment) => {
if (error) {
console.log(error)
callback(['databaseError'])
return
} else if (!comment) {
console.log(error)
callback(['notFound'])
return
} else {
callback([], comment)
}
})
}
/* in app.js */
app.delete('/comments/:commentId', (req, res, next) => {
const commentId = req.params.commentId
db.getCommentById(commentId, (errors, comment) => {
if (errors.length > 0) {
res.status(500).json({
message: 'serverError'
}).end()
return
} else if (!comment) {
res.status(404).json({
message: 'notFound'
}).end()
return
}
const accountId = req.accountId //from my auth middleware
const commAccId = comment.accountId
if(!commAccId) {
console.log(accountId)
console.log(commAccId)
res.status(404).json({
message: 'AccIdNotFound'
}).end()
return
}
- - - - - ^ this is the error checking I inserted, and this is where the error is thrown, so it seems like the id is just not found.
if(!accountId) {
res.status(401).json({
message: 'notAuthenticated'
}).end()
return
} else if (comment.accountId != accountId) {
res.status(401).json({
message: 'notAuthorized'
}).end()
return
}
//plus code for deletion (will insert if it seems relevant, just ask)
})
})
错误消息是“AccIdNotFound”
console.log 返回 5(与登录用户相同)且未定义
解决方案
db.all 提供一组行,而不仅仅是一行。您假设结果只是一条评论。
你应该检查result.length,然后拉出result[0]。
推荐阅读
- linux - OpenLDAP: Deleted user is still listed in the group
- python - 在列表中过滤字典
- parsing - 将类似的测试转换为具有变量的组
- r - 如何在 R 中使用 ggplot 更改散点图中刻度线的名称?
- kubernetes - 在 Google Cloud Function 中对 GKE 集群的 Kubernetes API 进行身份验证
- python-3.x - 由于代理,使用无法访问的网络安装 python
- jquery - 引导选择下拉菜单不能跟随父级
- angular - 错误:NullInjectorError:没有 FlashMessagesService 的提供者
- html - 标签与 HTML 中的元素有何不同
- multithreading - jmeter执行中的采样器依赖