req.params not giving anything in express nodejs

547 Views Asked by At

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

There are 3 best solutions below

1
jfriend00 On BEST ANSWER

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.

4
Shubham Vishwakarma On

First of all, you are missing Identifiers like let and const. Another thing, you have to now send the data with status.

Solution:

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

0
Akash On

Use this:

  res.send(`this is parcel with id: ${custId})`)
  

or this,

  res.json({
    message: `this is parcel with id: ${custId})`,
  });

You need to remember that res.send accepts a string. You can't use comma like that. If you want to contact your dynamic value with your string you can use + or template string.