02 - Express Router() intro
In this module, we'll create a few Express routes. Because an application can have dozens upon dozens of routes, the purpose of this is to help learn to create and organize our routes properly.
File Set up
Let's start by adding a controllers
folder and a testcontroller.js
file. We'll explain what controllers are later, but for now, add these two things:
testcontroller.js
Go into the
testcontroller.js
file.Add the following imports along with the
router.get()
function. Numbers are included for upcoming analysis:
Analysis
Let's take a look at what this code is doing. It's somewhat of a repeat of what we did in the last module:
We import the Express framework and it inside the variable
express
. This instance becomes our gateway to using Express methods.We use the
router
object by using therouter
variable to get access into theRouter()
object methods.get()
is one of the methods in the object, and we call it here. This method allows us to complete an HTTP GET request. We pass two arguments into the.get
method.The first argument is the path. In this case, the path is just a
/
. More on this later.The second argument is a callback function. This is also sometimes called a “handler function”. This function gets called when the application receives a request to the specified route and HTTP method. The application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
Inside our callback function, we call
res.send()
.send()
is an express method that can be called on theres
or response object. Our response parameter is just a simple string.We export the module for usage outside of the file.
app.js
Before this will work, we have to add routes into app.js
.
Go to
app.js
.Add the following code:
Analysis
We import the route object that we just created and store it in a variable called
test
.We call
app.use
and in the first parameter create a base url called/test
. So our base url will look like this:http://localhost:3000/test
For our second parameter for the
use()
function, we pass intest
. This means that all routes created in thetestcontroller.js
file will be sub-routes. It will look like this:http://localhost:3000/test
orhttp://localhost:3000/test/
Test
Let's test this now to get a better understanding. 1. Run the application using nodemon app.js
. 2. Open Postman. 3. In the url link, add the following route into the Request URL bar: http://localhost:3000/test/
4. Make sure that you have the request set to a GET request and press SEND. When you send, you should get a response like this:
Challenge #1
We could talk all day about this, but it won't make sense until you play around. Try the following: 1. Create a route that is the following url: http://localhost:3000/test/about
When you test the app in Postman, you should get a response like this:
Last updated