WittCode💻

Node and Express - Routes and Express Router

By

Learn everything about Express in this Node and Express tutorial series. This article goes in depth on Express routes and the Express Router object.

Table of Contents 📖

What is a Route?

In the previous article we got a small glimpse of routes in Express. A route is essentially a path on a website (/posts, /users, /home, etc.). Websites often have many routes that provide different resources, displays, etc. For example, one route could be used to display all the users registered on a website (/users), another could display all the posts (/posts), and so on.

Routes also have a HTTP request type. For example, a GET request to /users would be different than a POST request to /users.

Image

How to Create a Route in Express.js

To create a route in Express.js, we use app.HTTPmethod(path, handler). For example, if we want to handle a HTTP GET request to /users we would do the following:

app.get('/users', (request, response) => {});

So in that function signature, method is the HTTP request type (GET, POST, PUT, etc.), path is the path to the route, and handler is the callback function that accepts the request from the client and the response that our Express application sends back.

Adding more Routes

Lets change the response of our home route (/) and also add the route /users.

app.get('/', (request, response) => {
    response.send('<h1>Welcome to the homepage!</h1>');
});

app.get('/users', (request, response) => {
    response.send('<h1>This is the users page!</h1>');
});

Now, lets navigate to the home page (/) and users page (/users) in the url bar of our browser. We also need to make sure our server is still running with "nodemon index.js."

Image

HTTP GET Method

So far we have only been using the HTTP GET method. The HTTP GET method is used to retrieve data. For example, when we submit a HTTP GET request to /users we are requesting the data at /users. In this application, this is the string "This is the users page!". In a real world application, a GET request to /users would most likely return a list of all the users registered to the application.

HTTP POST Method

The HTTP POST method asks the web server to accept the data enclosed in the body of the request. For example, a POST request to /users could contain information about a new user in the request body. Our Express application could then use the information enclosed in the request body to create a new user and add them to the list of registered users.

Creating a HTTP POST Route with Express

So we can see that the HTTP method plays a big role in what will happen at that route. So lets create a POST route in our Express application.

app.post('/users', (request, response) => {
    response.send('You have accessed the users route with the POST method!');
});

So we can see that the structure of the route is the exact same, we can even just send back a string like we did with the HTTP GET method. However, to access this route we can't just type into the url bar of our browser "localhost:1234/users" as that will just access the route with the HTTP GET method.

How to Access a POST Route

To access the POST route, we can either use a handy tool like Postman or we can use curl in the command line. For this series we will be using our command line. So open up a command prompt and type in the following.

curl -X POST "http://localhost:1234/users"

Image

What is curl?

Curl is a command line tool used to transfer data between a client and a server. Specifically, we use -X POST to specify the HTTP request method as POST and then supply the path that we want to make the POST request to.

Common Usage of HTTP POST Requests

Of course, in commercial web applications we aren't pulling up command prompts to access certain routes. The way POST requests are often sent is through HTML forms.

<form action="/users" method="POST">

    <input type="text" id="username" name="username">

    <input type="password" id="password" name="password">

    <input type="submit" value="Log In">

</form>

In the code above, we are accepting a username and password and sending them off to the /users POST route for processing. This would most likely be for logging a user into the web application.

Other HTTP Request Methods

There are more HTTP request types than just POST and GET. For example, the HTTP DELETE method is used to delete a resource from the server while the HTTP PUT method is used to update data stored on the server. Now, lets say a user wants to update their profile information such as relationship status. We could issue a PUT request to get this done. We will be experimenting with other HTTP methods as this series continues.

Express All Method

Express also has a wildcard HTTP method called "all". This "all" method handles all types of HTTP methods be it POST, GET, DELETE, etc.

app.all('/my-route', (request, response) => {
    response.send('This route could have been accessed with any HTTP method!');
});

Image

Express Router

Now lets talk about an important class in Express called Express router. The Express router helps us create better route handlers. For example, writing the routes as we did above can get quite tedious if the path becomes long or complicated. This is why Express router provides us with an easier way to handle routes.

Creating Routes with Express Router

Lets first create a folder called routes at the top of our folder structure and within that make two more folders called users and posts. In each of these lets add an index.js file.

Image

Now, inside users/index.js lets add the following.

const express = require('express');
const router = express.Router();

router.get('/', (request, response) => {
    response.send('<h1>This is all the users!</h1>')
});

router.get('/wittcode', (request, response) => {
    response.send('<h1>This is wittcode's profile!</h1>');
});

module.exports = router;

From this code we can see how the Express router can be used to organize our routes. For example, we add each route to our router object and then we export it. Once we import this router object into our main index.js file (which we'll do in a bit), the routes localhost:1234/users and localhost:1234/users/wittcode will be added to our Express application.

An Express Router is a Mini App

Remember how calling express() creates an Express app? Well think of express.Router() as creating a mini app. Routes can become fairly complicated, so these mini apps allow us to separate our routes into different files and just clean things up.

Creating another Express Router

Lets add the following to posts/index.js.

const express = require('express');
const router = express.Router();

router.get('/', (request, response) => {
    response.send('<h1>This is the home page of the posts.</h1>')
});

router.get('/most-popular', (request, response) => {
    response.send('<h1>These are the most popular posts.</h1>');
});

module.exports = router;

The routes the code above adds are localhost:1234/posts and localhost:1234/posts/most-popular. Thanks to the Express router class we can divide our routes up into separate files like this. If we made all these routes in our main index.js file and not by using the Express router, we would have to write out each route in full and it could get fairly messy.

Importing our Router Objects

Inside our main index.js file lets add the following.

const users = require('./routes/users');
const posts = require('./routes/posts');

app.use('/users', users);
app.use('/posts', posts);

Here, we are requiring the users and posts folders that we created. We are actually requiring the index.js files in each but if we require a folder Node will, by default, look for an index.js file. Remember, both of these files export an Express router which is a mini app. These mini apps are then added to our main app in this file. We then have our usual handler for HTTP GET requests to the root (localhost:1234/).

What is app.use?

The method app.use is called every time a request is sent to our Express application. So, app.use('/users', users) will use our index.js file in our users folder everytime the /users route is accessed and app.use('/posts', posts) will use our index.js file in our posts folder everytime the /posts route is accessed.

Specifically, the method app.use takes something called middleware. We will not go into what that is in this article but we will soon. But for now, know that middleware is something that will run between the time the server gets a request from the client and the server sends a response to the client.

Image

Summary

But there we have it! In the next article we will be going over dynamic routes. So until then thanks for checking out this article and please consider supporting me by clicking on the donation button at the top of the page so I can keep making this sort of content!