Introduction
When we use the GPS in our car we put in a certain destination. the GPS then gives us a route to take to get to our destination. If we deviate from that route the GPS re-routes us to get to that same endpoint. Webpages are the same in that, when we put in a specific endpoint on a site the server routes the request to a certain file in our code to handle that request. We will look at a framework that makes this possible.
What is Express
Express is a free unopinionated node.js framework whose features allow for building out an application. Some features of using express includes: routing, handling middleware, creating API's, rendering HTML view, and many more things. The thing we will focus on today is routing.
Routing
When a client makes a request for information, it is usually to a specific endpoint. For example, if we search www.google.com/ we are routed to googles home page. if we add '/imghp' to the endpoint then google servers will reroute us to the google image home page. Routing is used to determine how an application responds to a client request to an endpoint and a specific HTTP request methods such as get, post, put, and patch. We can have different http methods on a specific endpoint, but we can have the same methods on the same endpoint. for example, two GET methods both routing to the same endpoint. Let us look at an example of establishing a route in a index.js file.
Routing example
In the example above, we first need to require express in our files. Once express is required we can set a variable like app to express and use that whenever we want to utilize a method. Each route can have one or more handler functions, which tells our server what to do when a request to the specific endpoint is made. most of the time we can route it to a specific file that will handle all the functionality.
Route Chaining
Having multiple routes to various endpoints can become space consuming. Let us look at an example of having multiple multiple routes:
In this example we have multiple routes set up. As we can see some of these routes are to the same endpoint. Express gives us a method called route that gives us a way to chain on HTTP methods that go with the same endpoint. Letβs look at how we would chain on these methods using the express route method.
In the example above, we have our app.route() method. Inside of that we can put our route. Next, we can chain on multiple HTTP methods to that one route. This frees up a lot of space and allows us to reuse code.
Conclusion
In conclusion, Express gives us a way to organize our code in a way that we can handle requests to endpoints in a certain way that benefits our MVC style. We start of by importing express into our files. and organizing our in a file. when the request is routed to the handler it can execute according to the code we built.
Top comments (0)