Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js : Express app.get with multiple query parameters

I want to query the yelp api, and have the following route:

app.get("/yelp/term/:term/location/:location", yelp.listPlaces)

When I make a GET request to

http://localhost:3000/yelp?term=food&location=austin,

I get the error

Cannot GET /yelp?term=food&location=austin

What am I doing wrong?

like image 925
tldr Avatar asked Sep 26 '13 05:09

tldr


People also ask

What is the use of APP get (*) in Express?

The app. get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions.

How can you capture query params sent by GET method?

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.


3 Answers

In the requested url http://localhost:3000/yelp?term=food&location=austin

  • base url/address is localhost:3000
  • route used for matching is /yelp
  • querystring url-encoded data is ?term=food&location=austin i.e. data is everything after ?

Query strings are not considered when peforming these matches, for example "GET /" would match the following route, as would "GET /?name=tobi".

So you should either :

  • use app.get("/yelp") and extract the term and location from req.query like req.query.term
  • use app.get("/yelp/term/:term/location/:location") but modify the url accordingly as luto described.
like image 173
user568109 Avatar answered Oct 10 '22 00:10

user568109


Have you tried calling it like this?

http://localhost:30000/yelp/term/food/location/austin

The URL you need to call usually looks pretty much like the route, you could also change it to:

/yelp/:location/:term

To make it a little prettier:

http://localhost:30000/yelp/austin/food
like image 35
luto Avatar answered Oct 10 '22 02:10

luto


I want to add to @luto's answer. There is no need to define query string parameters in the route. For instance the route /a will handle the request for /a?q=value.

The url parameters is a shortcut to define all the matches for a pattern of route so the route /a/:b will match

  1. /a/b
  2. /a/c
  3. /a/anything

it wont match

/a/b/something or /a

like image 4
Akshat Jiwan Sharma Avatar answered Oct 10 '22 00:10

Akshat Jiwan Sharma