Introduction to routing in Expressjs
Overview
Routing describes how URI endpoints in an application react to client requests. Routing is the most important component of a web application because, without a proper API to handle requests and the ability to know the pieces of the puzzle, you will end up with a code base that no developer wants to look at. Let's learn how to efficiently and effectively organise routes in Express to expand our backend without going crazy.
Introduction
The word "routing" describes the process of deciding how an application will respond to a client request for a particular path and HTTP request type. (GET, POST, and so on). You specify routing using Express app object methods that are equivalent to HTTP methods, such as an app.get() for GET requests and app.post() for POST requests, etc. 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.
In actuality, the callback functions that are input to the routing methods can be multiple. With numerous callback functions, it is crucial to pass control to the next callback by passing next as an parameter to the callback method and then calling next() inside the function body.
What is Routing?
Routing, put simply, is deciding which process is launched whenever a user navigates to a specific URL.
What are the Routing Methods?
A route function is derived from one of the HTTP methods and is attached to an express class instance.
Routing methods are defined as follows:
This method instructs the server to execute the next CALLBACK function and send an HTTPMETHOD request if the user navigates to PATH.
Here, the following verbs are used in place of METHOD:
Get: To process GET requests (that is, to request/GET data from a given resource).
Post: To send info to a server to update an old resource or create a new resource.
Put: To send info to a server to create/update a resource. POST requests vary from PUT requests in that the latter are idempotent. This implies that if a PUT request is made multiple times, it has no additional effect. In comparison, calling a POST method more than once will cause side effects in your programme. As a result, keep in mind that POST requests should only be made once.
Delete: To remove a specific resource from the database.
Head: Like a GET request, the HEAD method asks that the target resource transfer a representation of its state, but without the representation data enclosed in the response body. This helps retrieve representation metadata from the response header without transferring the complete representation.
Connect: The connect method instructs the intermediary to create a TCP/IP tunnel to the origin server specified by the request destination. It is frequently used to secure communications via one or more HTTP proxies.
Options: The options method asks the destination resource to send the HTTP methods it supports. This can be used to test a web server's functionality by requesting * instead of a particular resource.
Trace: The trace method asks that the received request be transferred to the target resource in the response body. A client can then see what modifications or additions (if any) have been made by intermediaries.
Patch: This function requests that the target resource modify its state based on the partial update specified in the request's representation. This can save bandwidth by updating a portion of a file or document without transferring the complete thing.
Examples of the most frequently used are:
All HTTP request mechanisms are supported by Express, like get, post, put, delete etc.
app.all() is a special routing technique that loads middleware functions at a path for all HTTP request methods. , For example,, for requests to the route /xyz, whether using DELETE, POST, GET, OR PUT or any other HTTP request method supported by the http module, the following handler is performed.
What are Route Paths?
The destinations at which requests can be made are defined by route paths in conjunction with request methods. Strings, string patterns, and regular expressions can all be used as route paths.
Regular expression characters ?, +, *, and () are subsets of their regular expression equivalents. String-based paths take the hyphen (-) and dot (.) strictly.
If you must use the dollar ($) symbol, in a path expression, enclose it within ([ and ]). The path string for queries to /data/$book would be /data/([$])book.
Here are some instances of string-based route paths:
Requests will be routed to the main route, /, via this routed path.
This route path will match queries to /faqs.
Here are some instances of string pattern-based route paths:
This route path will match acd and abcd.
Route routes based on regular expressions examples
This route path will fit anything that contains the letter "b"
What are Route Parameters?
Route parameters are URL segments that are used to capture the values provided in the URL at their position. The recorded values are stored in the req.params object, and their keys are the names of the route parameters provided in the path.
Request URL: http://localhost:3000/users/1/books/22
Route path: /users/:userId/books/:bookId
req.params: { "userId": "1", "bookId": "22" }
To construct routes with route parameters, simply enter the route arguments in the path of the route, as shown below.
You can add a regular expression in parentheses (()) to have more control over the precise string that can be matched by a route parameter:
Request URL: http://localhost:3000/user/22 Route path: /user/:userId(\d+) req.params: {"userId": "22"}
What are Route Handlers?
To handle a request, you can provide numerous callback functions that act as middleware. The only difference is that these callbacks may use the next('route') to skip the remaining route callbacks. This mechanism can be used to impose preconditions on a particular route and then transfer the control to next routes if there is no cause to continue with the current route.
Route handlers can take the shape of a function, an array of functions, or a combination of the two, as shown in the examples below.
A route can be handled by a single callback method.
As an example:
A route can be handled by more than one callback method. (make sure you specify the next object).
As an example:
Conclusion
- The word "routing" describes the process of deciding how an application will respond to a client request for a particular path and HTTP request type. (GET, POST, and so on).
- A route function is derived from one of the HTTP methods and is attached to an express class instance.
- app.all() is a special routing technique that loads middleware functions at a path for all HTTP request methods.
- The destinations at which requests can be made are defined by route paths in conjunction with request methods.
- Route parameters are URL segments that are used to capture the values provided in the URL at their position. The recorded values are stored in the req.params object, and their keys are the names of the route parameters provided in the path.
- To handle a request, you can provide numerous callback functions that act as middleware.