What is routing?
In order to add more pages to our site, we need to create more routes. Routing refers to determining how your application responds to a client request.
In layman’s terms, consider a building which has four rooms. One has a doctor, the second an engineer, the third a lawyer and in the last one, a teacher. There is a person outside these rooms, sitting at a desk. When a customer arrives , let us assume he asks for the doctor. Then the person at the desk handles this request by taking him to room A where the doctor is. If a customer comes looking for an engineer, the desk person takes him to room B. And so on.
We’ve already defind our basic route in the home page with
express.router() acts like a mini application. We can call an instance of it and definte routes to it.
server.js file we’ll call an instance of the router, apply routers to it, and add routes to our main app.
adminRouter.get(‘’, function(,)) anatomy
adminRouter is a variable which holds reference to our express.router() object.
get('', function(,)) routes HTTP GET requests to the specified path with the specified callback functions.
Lets dissect the following
We tell our app that our
adminRouter has a path of
/admin. This means any route we make with our
adminRouter will have to start with
For our dashboard, the route is just
/ which means if we go to
https://localhost:1337/admin our web page will display with text
I am the dashboard! in it’s body.
Now you might be wondering what
res means. Well they stand for
response. In our example above
request.url will be
/ and the
request.method will be
response will be what we send back which is just some text.
Now back to our application. We can start our server with
nodemon and we can navigate to the following web pages:
Play around with what we’ve done today. See if you can change the
/admin/ patch to something else like
/app/ so the following links work:
You can find the source code to this project here.
In the next post in this series we’ll go ouver Route Middleware so we can do something before a request is prcoess. So we can do things like checking if a user is authenticated, logging data for analytics, or anything else we’d like to do. We’ll also go over routes with Parameters to add more functionality to our app. Save this project as we’ll continue building on it.