Thursday, May 21, 2020

ExpressJS Routes

ExpressJS Routes


Routing


A route is the piece of code that maps an HTTP verb (GET, POST, DELETE and so on.), a URL path/pattern, and a function that is called to handle that pattern. Routing is the mechanism of URL handling or how the application endpoints (URIs) responds to the client's requests. A route can have multiple handler functions.

A route can be defined as,

app.METHOD(PATH, HANDLER)


  • The app is an instance of express.
  • METHOD is an HTTP request method(get, post,etc) in lowercase.
  • PATH is a path on the server. 
  • HANDLER A handler function is called when the app receives a request to the given route and HTTP method. This is called “listening of requests”. Whenever, the request matches the provided route(s) and method(s), the specified callback function is called.


For example,

app.get('/', function (req, res) { 
res.send('Welcome to ExpressJS') 
}) 

//OR 

app.post('/', function (req, res) { 
res.send('Recieved a POST request') 
}) 

The routing methods can have multiple callback functions as arguments. But it is important to specify next as an argument to the callback function and then call next() within the body of the function to pass control to the next callback.

For example,

app.all('/someLocation', function (req, res, next) { 
console.log('Accessing the someLocation ...') 
next() // pass control to the next handler 
}) 





app.all() method


The app.all() is a special routing method, that can be used to load any of the middleware functions for any of the HTTP request methods.

app.all('/someLocation', function (req, res, next) {
  console.log('Accessing the someLocaton ...')
  next() // pass control to the next handler
})

The above handler is called for any requests to the route “/someLocation”, for any HTTP( GET, POST etc.) request method.


Define Route paths


The route path appended with a request method are is used to define endpoints for which the request can be received. The route path can be string, string patterns or regular expression.

+, ?, * , (, ) can be used to produce regular expressions. However, - and . are interpreted literally in paths. The $ character can be used by simply enclosing it within ([ and ]). For example “/item/$price” can be used as “/item/([$])price”.

For example, This route path will match abcd, abbcd, abbbcd, and so on.

app.get('/ab+cd', function (req, res) {
  res.send('ab+cd')
})