API Routing using ExpressJS Router 4.0

Kingsley Solomon
eliteng

--

ExpressJS is one of the most well known packages for Node.js. It is a web development framework that helps us create the great applications. It is also the E in the MEAN stack (MongoDB, ExpressJS, AngularJS, Node.js).

Overview

Express 4.0 comes with the new Router. Router is like a mini express application. It doesn't bring in views or settings, but provides us with the routing APIs like .use, .get, .param, and route.

Our sample project

To demo the usage of Routing in ExpressJS 4.0 i’m going to cover the following points step by step. At the end you will have complete code covering all scenarios. You can find the complete code on github here

  1. Basic routing.
  2. Basic middleware routing.
  3. Accessing parameter in routing.
  4. Route middleware for parameters.
  5. Handling 404 errors.
  6. Sample routes for application.
    I will be using POSTMAN to test the route, you can have it as a chrome extension
    Setup Server File
    We’ll only need two files for our application.
  • package.json
  • server.js
    For our simple application, firstly let’s initialize npm for our project so open the terminal and type npm init -y this automatically generates a packaage.json file where all our dependencies is stored, now its time to install express open the terminal and run
    npm install express --save, once the installation is complete then your package.json file should look something like this.We’ll house our routes in the server.js file. In the future we'll want to move these out into their own files to keep our application routes clean. you can check out Keeping API Routes Clean. Here’s our package.json file to define our dependencies.
{
"name": "express-routing",
"main": "server.js",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
"dependencies": {
"express": "~4.0.0"
}
}

As you can see we need to specify a start script that will be use to start up the server. let specify it within the scripts just after the test script.
"start": "node server.js"
Now its time to write our server.js as specified in the start script.

// server.js

// BASE SETUP
// ==============================================


const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

// ROUTES
// ==============================================


// sample route with a route the way we're used to seeing it

app.get('/', (req, res) => {
res.send('Welcome to our application');
});

// we'll create our routes here

// START THE SERVER
// ==============================================

app.listen(port, ((err) => {
if(err) return err;
console.log(`Server started on port ${port}`);
}));

Now our server is setup, Let’s take a look at the first example of handling route, we would like to handle a HTTP GET request method on the route /, which in this case is the homepage of our web application. we head over to the terminal and run npm start we should see a message log to the console Server started on port 8080. Open your browser and visit http://localhost:8080 we should see Welcome to our application

Basic Routing

We’ll be implementing some basic routing for our application such as the home and about page, let’s make use of the new express Router() method.

Router is the public API for express’s Router. It provides routing APIs for things like .use(), .get(), .param(), and .route(). We can then call our HTTP verbs on this and also able to add middleware to this specific route. let’s add this to our code.

...// we'll create our routes hereconst router = express.Router(); //get an instance of routerrouter.get('/', (req, res) => {
res.send('Welcome to our application');
});

// about page route (http://localhost:8080/about)
router.get('/about', (req, res) => {
res.send('Welcome to my about page!');
});
// apply the routes to our application
app.use('/', router);

Basic middleware routing

Middleware is any number of functions that are invoked by the Express.js routing layer before your final request handler. This could be things like checking if a user is authenticated or logging data for analytics. Read More on Middleware
Let’s create a middleware to print a message to our console every time a request is made. This will be a demonstration of how to create middleware using the Express Router.NOTE: {…} shows some codes have been collapsed to avoid repetition.
We’ll use router.use() to define middleware. This will now be applied to all the requests that’s been made to our application.

...
//get instance of the router
...
router.use((req, res, next) => {

// log each request to the console
console.log(req.method, req.url);

// continue doing what we were doing and go to the route
next();
});

Open the browser and go to http://localhost:8080 then we should see a message been logged to the console. The order you place your middleware and routes is very important. Everything will get triggered in the order that they appear. This means that if you place your middleware after a route, then the route will get triggered before the middleware and the request will end there which means the middleware was not triggered.

Accessing parameter in routing.

Another thing i will like to talk about is accessing parameter from a request query string, Let’s say we wanted to have a route called /greeting/:name where we could pass in a person’s name into the URL and the application would spit out Good day name!.

...
// route with parameters (http://localhost:8080/greeting/:name)

router.get('/greeting/:name', (req, res) => {
res.send('Good day ' + req.params.name + '!');
});

Now we can visit http://localhost:8080/greeting/maximuf and see our browser spit out Good day maximuf!

Route middleware for parameters.

Now let’s say we wanted to validate this name somehow. Maybe we’d want to make sure the name is not less than 6 characters or check if the name already exist in database. We would do that validation inside of route middleware. We’ll use a special middleware for this. Let check to make sure a user passes a a name with more 6 characters.

...
// route middleware to validate :name

router.param('name', (req, res, next, name) => {
console.log(typeof(name), 'hello');
if(name && name.length > 6) {
// once validation is done save the new item in the req
req.name = name;
// go to the next thing
next();
} else {
return res.send('name with less than 6 character does not exist');
}
});

Now when we hit the /greeting/:name route, our route middleware will kick in and be used. We can run validations and then we’ll pass the new variable to our .get route by storing it in req. We then access it by changing req.params.name to req.name.
Open the browser and visit http://localhost:8080/greeting/123 you should get ‘name with less than 6 character does not exist’.

Handling 404 errors (Not Found)

It would be nice if we could display a message to the user if the routes he/she is trying to visit does not exist. To do so we need to put one middleware at then end of all routes which will get executed when none of the routes above match. Here is a code to do so.

...
// Handle 404 error.

router.use("*", (req, res) => {
res.status(404).send('404');
});

As you can see, if the user tries to visit a route that does not exist a status code of 404 is set. Open your browser and try hitting some random route.You should get 404 displayed on the page. All HTTP status code can be found here

Sample routes for application

Lastly we are going to look at creating sample routes for our application. This is similar to using app.get, but we will use app.route. app.route is basically a shortcut to call the Express Router. Instead of calling express.Router(), we can call app.route and start applying our routes there.

Using app.route lets us define multiple actions on a single login route. We’ll need a GETroute to show the login form and a POST route to process the login form.

All the code for this tutorial can be found here — View Code

// ROUTES
// ==============================================

...
app.route('/login')
.get(function(req, res) {
// show the form (GET http://localhost:8080/login)
res.send('this is the login form');
})
.post(function(req, res) {
// process the form (POST http://localhost:8080/login)
console.log('processing');
res.send('processing the login form!');
});

...

Conclusion

You can use Express router to define and extend routing facility for your application. Router will not just help you to just organize and control the routes but also you can use multiple behaviour for same route depending upon HTTP method. With all the ways we can define routes, I’m sure that our applications will benefit going forward. Any opinion based on this, feel free to use the comment box below. Thanks

Check out the following resources to learn more

--

--

Kingsley Solomon
eliteng
Editor for

Hi there! I’m Kingsley Solomon, a software engineer, and an enthusiastic product designer. #fullstack #frontend #backend #JS #PHP — https://johnkingzy.dev