javascriptnode.jsexpressbackendreq

req.params not giving anything in express nodejs


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.