×
Community Blog Routing with Node.JS on Alibaba Cloud

Routing with Node.JS on Alibaba Cloud

In this tutorial, we will be examining the methods of routing using Node.js on Alibaba Cloud. Specifically, we will explore two methods and examples for the case study.

By Alex Mungai Muchiri, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

Hello, Node.JS lovers! In this tutorial, we will be examining the methods of routing using Node.js. Hopefully, you have already grasped the fundamental principles of Node.JS. We will be examining the essentials of Node.js routing using Express. Specifically, we will explore two methods and examples for the case study.

For most programming languages, routing is an essential component of programming techniques. Older routing applications were tedious and most cases prone to errors. However, modern programming languages use advanced methods that have made programming much easier to implement.

The Basics

Node allows various routing techniques and, in this study, we are going to look at the fundamentals of routing and two techniques. Commonly, Node.js routing is achieved through Express, URL as well as other packages. In this first part, we embark on the routing principles with Node.js using Express. By setting up a Node server, we will use an HTTP protocol to make requests to the server, which is the most basic routing principle. In all the methods discussed in this article, we are going to need NPN running on our machine.

Requirements

  1. A server set up using Node.js
  2. Express installed in your machine
  3. Using express to Initiate Node routing

Step 1: Setup a Node Server

http.createServer(function (request, response) {
    // Send the HTTP header
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
    // Send the response body as "Hello World"
    response.end('Hello World\n');
}) .listen(8081);

Step 2: Install the Express Package

Run the npm install command to install express in your server.

Step 3: Applying Express for Routing

In this introduction, we set a simple "Hello World" message.

var express = require('express')
var app = express()

app.get('/hello',function (req,res){
    res.send('hello world')
});

While in the example above we have used the GET method, you could also try out POST, DELETE, PUT or even PATCH

// POST method
app.post('/submit form', function (req, res) {
    res.send('POST request to the homepage')
})

Even in this basic introduction to Node.js routing, we have seen how the procedure is executed at the most basic level. It requires creating a Node server with a port listening for HTTP. Since you will be working on a local host, and probably have set your port as 4042, you will access http://localhost:4042.

Hitting that link requires the execution of the Express package to create an application instance that handles incoming HTTP requests. The coded instructions work in the same manner as a microframework. Alright, now we can try to implement an actual project using these principles in Node.js.

Your First Node.js Routing Project

This phase of the tutorial aims at using the basic principles learned above to implement a very simple Node app with Express. We have chosen to use EJS in this case, which is a template engine that enables generation of HTML markup. Basically, what it does is allow us to have HTML pages that all depend on the client's request. As we have seen in the above basics, routing simply entails directing a user from one place to another, or when dealing with data, taking data from one place to the route. This segment would be a bit quick but it will build on what we have already seen above.

Create Your Project

This project aims at building a simple but fancy website that explores the routing principle in practice.

Sounds quite simple right? Nonetheless, it's all we need for this exercise. We shall begin by creating the project and installing the required packages. Run the following commands to install them, that is if you have not already installed

npm install express
npm install ejs
Adding the dash dash save is also allows since it is automatically formatted by Medium, and in any case, storing it in the package.json file is unsuitable. The next component we need for our project is to require Express. Then, in our app.js file, we shall set view engine to EJS like so:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');

We then need to set the port where our app listens to requests like so:

app.listen(4080);

GET Requests

If you have made it this far, you are doing well and we are ready to receive and execute GET requests in or server. The HTTP protocol can allow various other methods but, in our case, we only use the GET request type to retrieve data from our server. Since we are handling the request in Express, we shall use the method shown:

app.get('/about', function(req, res) {
  res.render('contacts');
});

Basically, what we are telling our server, in this case, is that if someone hits www.mywebsite.com/contacts we should execute a function. The statement further states that our function incorporates req (request) and res (response) parameters. What our function does is render a contacts page using the response object.

In our little experiment, there needs to be an HTML page named contacts.ejs. Express will look in that folder to render a web view. Below we have a simple page that we shall use for this example.

1

This is the perfect scenario, but we need to look at other use cases such as when a user fails to type in any route. That should be fairly easy to handle as well. We are going to change the contacts option to about.

app.get('/', function(req, res) {
  res.render('about');
});

You should expect a default error response from the method.

What to Do with Non-Existent Routes

We are going to implement a custom error page for use in cases where someone types a route that does not exist. When using Express, making such a page is very easy. What we shall do is render a cool error page by using a GET method with an asterisk as shown:

app.get('*', function(req, res) {
  res.render('error');
});

We need to test and see if we are successful in our implementation by running our server from the command line node app. Since we are using a local server running on the machine, I will type in the local URL and a port in my browser like so:

localhost:4080 or localhost:4080/

2

localhost:4080/contacts

3

localhost:4080/wrong

4

Fantastic! We have successfully rendered a custom error page from our browser.

So far, we have looked at the fundamental routing principle in Node.js and also implemented our first routing project. If you need more information about Express or EJS visit their website for more information. We are now going to advance what we have learned in the second case study.

Implementing External Routes

In this second use case, we shall be setting up external routes for our Node.js server, which I assume you are comfortable setting up by now. So, why would anyone need external routes? If your code is getting increasingly complicated and difficult to read, you can use external routes maintain well-organized, easy-to-maintain, and easy to read the code. External routes are a great way to create neat code structures that are easy to examine.

We have already seen how to set up internal routes in our servers. However, you do not want to get to that level where everything is utterly confusing due to multiple routes in your server. What external routing does is remove route implementations from your server to a separate router file.

Sample implementation

We are going to assume that our server contains a file with several routes, say index.js:

    var express = require('express');
    var app = express();

    // The first route
    app.get('/', function (req, res) {
        res.send('Hello 1');
    });

    // The Second route
    app.get('/A', function (req, res) {
        res.send('Hello 2!');
    });

    // The Third route
    app.get('/B', function (req, res) {
        res.send('Hello 3!');
    });

    // The Fourth route
    app.get('/C', function (req, res) {
        res.send('Hello 4!');
    });

    // Listen to port 4800
    app.listen(4800, function () {
      console.log('Our app listens to port 4800!');
    });

If we were to add more routes to this file, it would increasingly become complex and hard to maintain. While we have four routes at the moment, over years, we can have it serving tens or even hundreds of functions. You can anticipate APIs, social media integration and many other functions. The aim of external routing is to separate and structure the code to be more niche to avoid having too much functionality in our index file since it may be used for much more in the future.

Goal of the Project

This project will help keep a clean index and well-organized code. What we shall do is separate route definitions from the main index file in a cleaner file/folder structure. To achieve this, we shall create an index.js file, a folder under it called routes and an externalRoutes.js in that folder:

.
├── index.js              
└── routes             
   └── appRoutes.js  

That's great so far, but we still have a few steps to go before our router is implemented

Define Our Router

Let us now clean up the index file and see how it goes. We shall replace all the given routes in our sample implementation with a single router definition. What the router definition does is define the location of routes. Specifically, the index searches for a file called appRoutes.js in the routes folder. The file has all the routing implementations. This is executed like so:

// Implementing external routes
var appRoutes = require('./routes/appRoutes');
app.use('/appRoutes', appRoutes);
The cleaner index.js file will have fewer functions
// index.js
var express = require('express');
var app = express();

// These are our external routes
var appRoutes = require('./routes/appRoutes');
app.use('/appRoutes', appRoutes);

// Listen to port 4800
app.listen(4800, function () {
  console.log('Our app listens to port 4800!');
});

This is much cleaner, isn't it? Just one last step remains to implement our router.

Implementation

Do not get worried about where our routes went to, all we need is store them in the appRoutes.js file. You will need to use the externalRoutes variable to create a module export to export definitions. In the appRoutes.js file, create a module.exports function like in the below:

module.exports = (function() {
    'use strict';
})();

Proceed to include the variable that we want to export in module.exports body, in our case we use the appRoutes:

module.exports = (function() {
    'use strict';

    var appRoutes = require('express').Router();

    return appRoutes;
})();

We then include the specific routes in the module.exports like so:

module.exports = (function() {
    'use strict';
    var appRoutes = require('express').Router();

    appRoutes.get('/', function (req, res) {
        res.send('Hello appRoutes!');
    });
    appRoutes.get('/someRoute', function (req, res) {
        res.send('Hello routeB!');
    });

    return appRoutes;
})();

Note: If you have problems when executing these instructions, simple replace 'appRoutes' in all instances with 'externalRoutes.'

Accessing External Routes in Browsers

We can now try to access those external routes via the browser using http://localhost:4800/appRoutes and http://localhost:4800/appRoutes/routeB.

Conclusion

Well done! You have learned the basics of Node routes, how to implement some simple routes and how to work with external routes. Your node server is very robust as we have seen in our last implementation. We have successfully cleaned the index file and created a structure for external routes. Not only did we create simple access routes but also built a robust and maintainable code framework.

References:

  1. https://nodejs.org/
  2. https://medium.freecodecamp.org/really-really-basic-routing-in-nodejs-with-express-d7cad5e3f5d5
  3. http://www.dotnetcurry.com/nodejs/1256/using-expressjs-implement-routing
0 0 0
Share on

Alex

17 posts | 2 followers

You may also like

Comments