Pulse Nova
Pulse Nova

Reputation: 327

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:

Get Request with the request id params passed

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

Executed Queries in 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:

Response from the executed query

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.

Upvotes: 1

Views: 641

Answers (2)

Ayush
Ayush

Reputation: 131

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);
    })
})

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074258

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);
    })
})

Upvotes: 2

Related Questions