1

I would like to get the url parameter and if url is defined wrongly by user, i need to send an error.

My url is: localhost:8080/user?id=1

If the url entered by the user is: localhost:8080/use?id=1, how do we handle it?

if (app.get("/user")) {
  app.get("/user",function(req,res,next){
    console.log('In');
  });
} else {
  console.log('something went wrong in url');
}
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
user3013170
  • 119
  • 1
  • 1
  • 5

4 Answers4

3

No need for an if/else statement. Simply list all of your paths, and add a default path at the end. If query does not match with any of your definitions, it will call the default path.

app.get("/user",function(req,res){
    res.send('called user');
});

... 

app.get("/*", function(req, res){
   res.send('wrong path');
});

Note that the order is important, if you put the "/*" at the top, it will dominate the others. So it has to be the last.

anvarik
  • 6,417
  • 5
  • 39
  • 53
0

You can parse req.url using parse function from url module:

Here is the example from node.js documentation:

node> require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan',
  search: '?name=ryan',
  query: 'name=ryan',
  pathname: '/status' }
Andrzej Karpuszonak
  • 8,896
  • 2
  • 38
  • 50
0

app.get is an event handler. The corresponding callback gets called only when a request matches that route. You don't need to specify an if statement for it. You need to do study a bit of javascript and how events/callbacks work. I think this article which looks decent.

Munim
  • 6,310
  • 2
  • 35
  • 44
0

app.get is an event handler. No need of the if condition. I prefer you to change the url from

localhost:8080/user?id=1

To

localhost:8080/user/1

If the path ie: localhost:8080/user/1 is not defined then the freamwork automatically display message

Cannot GET /user/1

app.get("/user/:id", function(req, res){
console.log('In userId = '+req.params.id);
}) ;

Note the :id, you can use this name to access the value in your code.If you have multiple variables in your url, for example

localhost:8080/user/1/damodaran

so your app.get will look like

app.get("/user/:id/:name", function(req, res){
console.log('In userId = '+req.params.id+' name:'++req.params.name);
}) ;

Check these links

expressjs api

Express app.get documentation

Community
  • 1
  • 1
Damodaran
  • 10,882
  • 10
  • 60
  • 81