Express.js Routing

Learn via video courses
Topics Covered

Overview

Routing in Express JS is the process of specifying how an application replies to a client request to a specific endpoint or URL. To run a function upon request for a certain route, route handlers are used. The Express Router allows developers to create routes and associated route handlers for various HTTP methods.

Introduction to Routing

Before we get started there are a couple of things you should be familiar with, here's a brief description for each of them:

  1. The APP, an instance of the Express.js class that builds routes to handle client requests, is the core object of an Express.js web application. Routes can be built for different HTTP methods, and middleware functions can be added to change the request and response objects.
  2. METHOD is a type of HTTP request. The uppercase word METHOD refers to the HTTP method of the request, such as GET, PUT, POST, and so forth. Thus, app.get(), app.post(), app.put(), and so forth are the real methods.
  3. The term PATH describes the part of a client request's URL that follows after the domain name and any port numbers. To match inbound requests to particular path handlers in Express.js, the Path is used. For Express.js to match a request's path to a registered route and run the relevant handler function, routes are specified using a combination of the HTTP method and URL path.
  4. When the route and method match, the callback code HANDLER is called. In actuality, the callback functions that are input to the routing methods can be multiple. With numerous callback functions, it is crucial to passing control to the next callback by passing next as an argument to the callback function and then calling next() inside the function body.

The way an application's endpoints (URIs) respond when a client requests something is referred to as routing

Routing can be defined using Express app object's methods that correspond to the HTTP methods just like how app.get() is used to handle GET requests and app.post() for handling POST requests. Moreover you can use app.all() for handling all HTTP methods and app.use() for specifying middleware as the callback function

Learn more about middleware in expressJs here

When the application gets a request to the specified route (endpoint) and HTTP method, it calls the callback function specified by these routing methods (also known as "handler functions"). To put it another way, the application essentially "listens" for requests that match the route(s) and method(s) specified, and when it finds a match, it executes the callback function specified.

The following code is an example of a very basic route

Route Methods

The common means by which clients interact with web servers are known as route methods, also known as HTTP methods, the type of requests are specified here.

Now, let's take an example where routes for GET and POST methods to the app's route are specified

All HTTP request techniques are supported by Express, including get, post, and others.

As mentioned earlier in this article, for all HTTP request methods, the special routing method app.all() is used to install middleware functions at a path. For instance, the handler listed below is used for requests to the route /secret, regardless of whether they are made using the GET, POST, PUT, DELETE, or any other HTTP request technique that the HTTP module supports.

Route Paths

The endpoints at which requests may be made are defined by route paths in conjunction with a request mechanism. Strings, string patterns, or regular expressions can all be used as route paths.

The symbols ?, +, *, and () are subgroups of their equivalents in regular expressions. By string-based paths, the hyphen (-) and the dot (.) should be taken strictly.

The path string for queries to /data/$book, for instance, would be /data/([$])book

Remember that the travel path does not include query strings. Here are some instances of string-based routes.

Requests to the main route, /, will be matched by this route path.

This route path will match requests to /about.

This route path will match requests to /random.text.

Let's now see some examples of route paths based on string patterns

  1. This route path will match acd and abcd.
  1. This route path will match abcd, abbcd, abbbcd, and so on.
  1. This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on
  1. This route path will match /abe and /abcde.

Examples of route paths based on regular expressions:

  1. This route path will match anything with an a in it.
  1. This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.

The locations at which requests can be made are specified by the route paths. The examples up to this point have all been strings that have been used precisely as they are written: /, /about, /book, and /any-random.path

String patterns can also be used as route paths. To specify patterns of ends that will be matched, string patterns use a variant of regular expression syntax. The syntax is as follows (notice that string-based paths take the hyphen (-) and the dot (.) literally):

  • ?:
    The endpoint must contain 0 or 1 of the letter (or group) before it; for example, a route path of /ab?cd will match either the endpoint acd or the endpoint abcd.
  • +:
    The endpoint must contain 1 or more of the preceding character (or group), for example, the route path /ab+cd will fit the endpoints abcd,abbcd, abbbcd, and so on.
  • *:
    The endpoint may contain any string instead of the * character. For instance, the endpoints abcd, abXcd, abSOMErandomTEXTcd, and so forth will all fit a route path of /ab*cd
  • ():
    Grouping match on a set of characters to be used in another operation;

For example, /ab(cd)?e will execute a?-match on the group (cd) and match the characters abe and abcde

The route paths could also be regular expressions written in JavaScript. The route path below, for instance, matches catfish and dogfish but not catflap, catfish head, etc. Syntax for a regular expression is used in the path for the regular expression. (it is not a quoted string as in the previous cases).

Route Handlers

A single HTTP transaction can be roughly described by the Request and Response cycle.

  • The server receives a message from the client.
  • After receiving the request, the server reads the info. (request headers, URL path, HTTP method, query parameters, cookies, data or payload, etc.).
  • The client receives a reply from the server. The status number, headers, content encoding, and any returned data are all included
  • The HTTP transaction is finished once the answer has been returned.

Multiple middleware functions can be used to process a request, with the ability to bypass the remaining callbacks by invoking the next('route'). This can be useful to set conditions on a route and then move on to other routes if necessary.

Route handlers can take various forms, such as a single function, an array of functions, or a combination of both.

A route can be handled by a single callback method. For instance:

Multiple callback methods can be employed to handle a route, with the condition that the next object is properly defined.

Let's see an example to help you understand better,

An array of callback functions can handle a route. For example:

A combination of independent functions and arrays of functions can handle a route. For example:

Response Methods

The request-response cycle can be ended by using the methods on the response object (res) in the accompanying table to send a response to the client. The client request will be abandoned if none of these techniques are used by a route handler.

MethodDescription
res.download()Prompt a file to be downloaded.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus()Set the response status code and send its string representation as the response body.
res.end()End the response process.
res.json()Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.

Express.Router

The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.

Syntax:

Optional Parameters:

  • case-sensitive:
    This enables case sensitivity.
  • mergeParams:
    It preserves the req.params values from the parent router.
  • strict:
    This enables strict routing.

Return Value:
This function returns the New Router Object.

Explanation and Example
Modular, mountable route controllers can be made using the express.Router class. A Router instance is frequently referred to as a "mini-app" because it is an entire middleware and navigation system.

The example that follows shows how to build a router as a module, load a middleware function, define a few routes, and mount the router module on a path in the main app.

We must first build a separate module, instantiate an instance of app.Router, and use module.exports to export the instance before we can use app.Router().

In the app subfolder, create a router file called "birds.js" and fill it with the following information:

Then, load the router module in the app:

The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

Example to See Basic Routing

The following examples illustrate defining simple routes.

Example 1
Respond with Hello World! on the homepage:

Example 2
Respond to POST request on the root route (/), the application’s home page:

Example 3
Respond to a PUT request to the /user route:

Example 4
Respond to a DELETE request to the /user route:

Example 5:
Let's create a file named index.js

Now make a GET request to

  1. http://localhost:3000/user,
  2. http://localhost:3000/admin, and
  3. http://localhost:3000/student,

then you will see the following output on your console:

Output:

Example 6
Chainable Routes with app.route()

With app.route() you can chain route handlers for a route path. Creating modular routes is helpful because it is reducing redundancy and typos.

Let's have a look at an example of chained route handlers:

Conclusion

  1. METHOD is a type of HTTP request. The uppercase word METHOD refers to the HTTP method of the request, such as GET, PUT, POST, and so forth
  2. The endpoints at which requests may be made are defined by route paths in conjunction with a request mechanism. Strings, string patterns, or regular expressions can all be used as route routes.
  3. The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.