user3013170
user3013170

Reputation: 119

How to handle GET parameter in Express?

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

Upvotes: 1

Views: 308

Answers (4)

Damodaran
Damodaran

Reputation: 11047

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

Upvotes: 0

Munim
Munim

Reputation: 6510

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.

Upvotes: 0

anvarik
anvarik

Reputation: 6487

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.

Upvotes: 3

Andrei Karpuszonak
Andrei Karpuszonak

Reputation: 9034

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' }

Upvotes: 0

Related Questions