why i am getting cannot GET error in mongo db postman while i am using query parameter

I am trying to request a query through the router but I didn't get

router.get('/questions/:id',(req,res) => {
    console.log(req.query)
    res.send(req.query) 
})

I want to get req. query but while sending a request through postman it is showing Cannot GET/questions I don't know why but thanks in advance. enter image description here

Upvotes: 0

Views: 32

Answers (1)

samthecodingman
samthecodingman

Reputation: 26306

The error is telling you that you cannot get the path /questions. This is because you have implemented /questions/someId and not /questions?id=someId.

// slash syntax
router.get('/questions/:id', (req, res) => {
    console.log(`Got via parameter syntax: id=${req.params.id}`)
    res.send(req.params.id);
})

// query syntax
router.get('/questions', (req, res) => {
    if (typeof req.query.id !== "string") {
        res.status(404).send("Missing required query parameter: id");
        return;
    }
    console.log(`Got via query syntax: id=${req.query.id}`)
    res.send(req.query.id);
})

You can also support both in the same chain:

// dual query & slash syntax
router.get(['/questions', '/questions/:id'], (req, res) => {
    const id = req.params.id || req.query.id;
    if (typeof id !== "string") {
        res.status(404).send("Missing required parameter: id");
        return;
    }
    res.send(id);
})

Upvotes: 1

Related Questions