简体   繁体   中英

Unable to fetch the available data with the request params id in node.js

I have a following get request on the server:

payments.get('/:id', (req, res) => {
    Payment.findAll({
        where: {
            requestID: req.params.id
        }
    })
    .then(res => {
        res.status(200).json({status: "Ok", res})
    })
    .catch(err => {
        res.status(404).json({status: false});
        // res.send(err);
    })
})

When I test to get all the payment details from the given request params id in postman then I failed to fetch the available data from the database and it always runs to the catch() function as shown in the figure below:

使用传递的请求 ID 参数获取请求

When I hit the Send button in postman, my nodejs console will execute the following query function:

Sequelize 中执行的查询

When I tested this query in the XAMPP Server, then it shows the data.

SELECT `payment_id`, `stud_uuid` AS `studID`, `request_id` AS `requestID`, `request_date` AS `requestDate`, `amount`, `ins_uuid` AS `insID`, `status` FROM `tbl_payment` AS `tbl_payment` WHERE `tbl_payment`.`request_id` = 'd690ae99-c6bf-4568-ad2b-980bfb4696e8'

The data is as follows:

来自已执行查询的响应

What I am missing in the nodejs function that I am unable to show the available data?? Why my get request is always going to the catch() statement.. Any help is appreciated.

The problem is here:

payments.get('/:id', (req, res) => {
    Payment.findAll({
        where: {
            requestID: req.params.id
        }
    })
    .then(res => {
// −−−−−−−^^^
        res.status(200).json({status: "Ok", res})
    })
    .catch(err => {
        res.status(404).json({status: false});
        // res.send(err);
    })
})

You're shadowing the res you received in the get callback with the result of the promise. Rename it:

payments.get('/:id', (req, res) => {
    Payment.findAll({
        where: {
            requestID: req.params.id
        }
    })
    .then(result => {
// −−−−−−−^^^^^^
        res.status(200).json({status: "Ok", res: result})
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^
    })
    .catch(err => {
        res.status(404).json({status: false});
        // res.send(err);
    })
})

Problem is res being used here promise resolution object of Payment.findAll , instead use some other variable so that res doesn't get overridden.

payments.get('/:id', (req, res) => {
    Payment.findAll({
        where: {
            requestID: req.params.id
        }
    })
    .then(**done** => {
        res.status(200).json({status: "Ok", **done**})
    })
    .catch(err => {
        res.status(404).json({status: false});
        // res.send(err);
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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