How to access route parameters in node.JS?

775 Views Asked by At

I want to access the route parameters in Node.JS and I am using the following syntax:

app.get("posts/:postName", function(req,res){
  console.log(req.params.postName)
});

Is something wrong in the syntax? The error I get in the browser is, "Cannot GET /posts/print". Over here, print was the key-word I chose.

3

There are 3 best solutions below

0
On

Your code is missing /

app.get("/posts/:postName", function(req,res){
  console.log(req.params.postName)
});

0
On

make sure you have one get rout if dont what to use "?" at the end this will make sure your this value of post name is in the rout or not and them put them in a sequence like enter image description here app.get("posts/:postName?", ( req, res ) => {})

as first rout is with no data in rout and rout below has data in rout with specific attribute

0
On

To access route parameter you have to use req.params.parameterName and access query string you have to use req.query.parameterName

Please modify your route like this -

app.get("/posts/:postName", function(req,res){
  console.log(req.params.postName)
});

Suppose if you are trying to access page and limit from url like this http://example.com/**?page=2&limit=20**, then for page use req.query.page and for limit use req.query.limit