Why is URL recognized by Express.js not like the usual URLs that we see?



Why is a URL that is recognizable to Express.js, not like the usual URLs we see?

For example:
Express.js will recognize this URL (http://localhost:3000/things/0) where id=0 if I make this GET request:

app.get('/things/:id', (req, res) => {
   // Do somethihng

But this URL (http://localhost:3000/things/?id=0) which is more like the usual URLs we see won’t work for the same GET request above.


So, "normal URLs" is apparently in the eye of the beholder as there are really just different styles, neither being any more normal than the other.

There are a couple ways to pass parameters in a URL.

#1 – You can embed it in the path of the URL


This is referred to as a RESTFUL design. These URLs contain a noun and then an id that identifies which of those nouns the URL refers to.

#2 – You can put the variable part of the URL in a query parameter

For those same two URLs above, that could look like this:


There are valid reasons for both designs depending upon circumstances and there are even cases where you combine the two (add optional query parameters to the restful API designs in option #1. Neither one is "normal" – they are different ways to design your URLs.

Express allows you to use either one. For restful parameters that are in the path of the URL, you use the :id syntax and you access the value in req.params.id:

app.get('/things/:id', (req, res) => {

For query parameters, you don’t define them in the express route path. Instead, Express parses any query parameters that exist on any route and makes them available in req.query.

// expecting /things?id=789&sort=alpha
app.get('/things', (req, res) => {
   console.log(req.query.id);            // "789"
   console.log(req.query.sort);          // "alpha"

Any query parameter that is present in the URL will be added to the req.query object.

Note that query parameters are often considered optional and thus you don’t code them into your route definition. If you want to require a specific query parameter, then you have to check if it’s there and, if not, then provide some error response or call next() to continue to routing to other request handlers.

FYI, there’s another style that often uses client-side code to help build that page and puts URL arguments in a hash tag too, but I’ll leave that for another day.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More