简体   繁体   English

通过 Rest API 使用用户 ID 提取用户数据

[英]Pulling user data using by Rest API with userID

I am trying to pull logs belonging to a logged in user from my database.我正在尝试从我的数据库中提取属于已登录用户的日志。 I think I have the id set-up correctly in the route however I am not sure where I am going wrong with the controller API.我认为我在路线中正确设置了 ID,但是我不确定 controller API 哪里出了问题。 In Postman it is returning the catch error message and there are definitely entries in the database belonging to the user number.在 Postman 中,它返回捕获错误消息,并且数据库中肯定有属于用户号的条目。

I have tried a few variations but keep getting the same error.我尝试了一些变体,但不断收到相同的错误。 Is this the way my API is set-up这是我的 API 的设置方式吗

exports.userDiveLog = (req, res) => {

    const id = req.params.id;

    diveLog.findAll({
        where: {diverUserNumber: id}
    })
        .then(diveLog => {

            const userDiveLogList = [];
            for (i = 0; i < diveLog.length; i++) {
                userDiveLogList.push(diveLog[i].dataValues);
            }

            if (!userDiveLogList) {
                return res.status(404).send({ message: "No dive logs belonging to this user" });
            }

        res.status(200).send({
            data: userDiveLogList
        })
    })
        .catch(err => {
            res.status(500).send({
                message: "Error retrieving dive log belonging to user id= " + id
            });
        });
};

route路线

app.get('/api/divelog/userdiveloglist/:id', controller.userDiveLog);

在此处输入图像描述

Corrected as I hadn't properly inserted a try catch loop.已更正,因为我没有正确插入 try catch 循环。

exports.userDiveLog = (req, res) => {

    try {
        const id = req.params.id;

        diveLog.findAll({
            where: {diverUserNumber: id}
        })
            .then(diveLog => {

                const userDiveLogList = [];
                for (i = 0; i < diveLog.length; i++) {
                    userDiveLogList.push(diveLog[i].dataValues);
                }

                if (!userDiveLogList) {
                    return res.status(404).send({message: "No dive logs belonging to this user"});
                }

                res.status(200).send({
                    data: userDiveLogList
                })
            })
    } catch(err) {
            res.status(500).send({
                message: "Error retrieving dive log belonging to user id= " + id
            });
        }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM