req.params not giving anything in express nodejs

Issue

I am trying to use the following code to get Id in the url. The problem is that req.params is not giving anything from the route.

app.get("/getAllParcels/:Id",(req,res) => {
        custId = req.params.Id;
        res.send('this is parcel with id:', custId);
});

Solution

The Express version of res.send(), only takes one argument so when you do this:

app.get("/getAllParcels/:Id",(req,res) => {
        custId = req.params.Id;
        res.send('this is parcel with id:', custId);
});

it’s only going to do this (only paying attention to the first argument):

res.send('this is parcel with id:');

Instead, change your code to this:

app.get("/getAllParcels/:Id",(req,res) => {
    const custId = req.params.Id;
    res.send(`this is parcel with id: ${custId}`);  
});

Note, this properly declares the variable custId using const and it uses a template string (with backquotes) to efficiently incorporate the custId.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published