Ylama
Ylama

Reputation: 2489

Node api GET status request

Im fetching the ID and current status of the item, it works, but i want to do a check to see if its active or not meaning if active: false then return -> status 404 , message: Status not active.

My problem is i cant seem to get the active returning from the request, im new to this so maybe im understanding it wrong or making a simple mistake, thanks for help in advance.

Document:

{
     "_id" : ObjectId("5b3f7b2efe8d1f3ef8096dfd"),
     "name" : "Brand Name",
     "active" : false,
     "__v" : 0
}

Code:

// RETURN ACTIVE STATUS OF SINGLE BRAND FROM DATABASE

router.get('/:id/ActiveStatus', (req, res) => {
    var id = req.params.id;

    //MY ATTEMPTED TO GET THE ACTIVE STATUS = undefined  
    var status = req.query.active;
    console.log(status);

    if(status !== true){
        return res.status(404).send({message: 'Status not found.'});
    }

    if(!ObjectID.isValid(id)){
        return res.status(404).send({message: 'Invalid Object ID provided.'})
    }

    Brand.findById(id, {active: 1}).then((brand) => {
        if(!brand){
            return res.status(404).send({message: 'Error, status not active.'})
        }
            res.send({brand});
    }).catch((e) => {
        return res.status(404).send(e);
    });
});

Upvotes: 0

Views: 331

Answers (1)

Firoz Shams
Firoz Shams

Reputation: 162

//MY ATTEMPTED TO GET THE ACTIVE STATUS = undefined  
var status = req.query.active;

If you want to get the status parameter then according to your code, the client will have to provide it when calling your api. So the client api call should be -

https://<url>/<id>/ActiveStatus?active="some value"

After which you can access it like the way you did in your code.

var status = req.query.active;

If you want to get it from request parameters you can define your route like this

// RETURN ACTIVE STATUS OF SINGLE BRAND FROM DATABASE

router.get('/:id/ActiveStatus/:active', (req, res) => {
    //your code
});

In this case you can access it via the request parameter much like you did for the id

var status = req.params.active;

Upvotes: 1

Related Questions