首页 > 解决方案 > 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(与登录用户相同)且未定义

标签: node.jssqliteexpress

解决方案


db.all 提供一组行,而不仅仅是一行。您假设结果只是一条评论。

你应该检查result.length,然后拉出result[0]。


推荐阅读