-2

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 Answers3

1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @syedhaseebahmad - Glad it worked for you. Since it looks like you're new here, you can indicate to the community here that your question has been answered by clicking the checkmark to the left of whatever answer helped you the most or was the most comprehensive or clearest. That will also earn you a few reputation points for following that part of the process. – jfriend00 Oct 08 '22 at 17:54
1

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.

Akash
  • 21
  • 1
  • 4
-2

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}`);
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Your comments about `res.send()` being deprecated or requiring the status are just wrong. This has nothing to do with nodejs version 18 as these are Express features. – jfriend00 Oct 06 '22 at 22:25
  • Hey, My bad, FIxed it – Shubham Vishwakarma Oct 06 '22 at 22:26
  • Your comments about Express deprecating `res.send()` without status are still wrong. It's all shown right [here](http://expressjs.com/en/4x/api.html#res.send) in the Express doc. – jfriend00 Oct 06 '22 at 22:28
  • `res.send()` is not deprecated in express. In fact you're still calling it in your example! You're just chaining it off another method, which makes no difference and the `res.status()` is unnecessary anyway as the 200 status would be the default. – gigabates Oct 06 '22 at 22:33