Deploying Node.js microservices to ZEIT ▲ Now

Deploying Node.js microservices to ZEIT ▲ Now

<strong>ZEIT Now is a cloud platform to deploy serverless applications, one of the things I like the most about Now is their DX (Developer Experience), it makes it very pleasant to deploy microservices to the cloud.</strong>

ZEIT Now is a cloud platform to deploy serverless applications, one of the things I like the most about Now is their DX (Developer Experience), it makes it very pleasant to deploy microservices to the cloud.

In this article we are going to learn how to install Now and start deploying with one single command, now.

Prerequisites
  • Node.js 10 LTS Installed
  • A terminal
  • Code editor of your choice
  • A ZEIT Now account, you can signup for free here
Installation

First, let’s install now CLI from npm by running the following command:

$ npm install -g now

Login

Next, we need to identify ourselves in the platform, now CLI offers an easy way to do this by running:

$ now login

This will ask for your email and will send you a Verification email, just by clicking on Verify will log you in the platform, it’s like magic 🔮!

Verifying email

Successful login from Terminal


Create your first Microservice

We are ready to start creating our first microservice (or serverless application, you name it).

Now provides a list of examples, for our exercise we are going to use Node.js ⬢, but hey!, Now supports other languages and platforms too, just give it a try with the one you like the most 😉

To start witht he Node.js template let’s run the following command:

$ now init nodejs microservice

This will create a folder called microservice with the Node.js template.

Now is time to deploy our example to the cloud, let’s go to that folder and execute now to see what happens!

$ cd microservice
$ now

Deploying to Now and running our microservice

Before continuing with our next trick, let’s explore the files we are deploying:

index.js

It contains a simple function with the request and response objects from Node.js, this will be executed on every request made to our microservice.

module.exports = (req, res) => {
res.end(Hello from Node.js on Now 2.0!);
};

index.js


now.json

It’s the deployment configuration file, used to specify the name of our project, the type of builders we are going to use, routes, etc. More information can be found in their documentation.

{
"version": 2,
"name": "nodejs",
"builds": [
{ "src": "*.js", "use": "@now/node" }
]
}

now.json


Monorepo

What we have seen so far seems simple, but, here comes the real power of now, we can mix and match different microservices in a monorepo to create a full serverless project.

For our next trick, we will create a Nuxt.js static application that will be doing API requests to a Node.js microservice, both are going to be deployed to now using the monorepo approach.

Let’s create a monorepo folder and then run create-nuxt-app, this will create a basic Nuxt.js application for you, just make sure to select Axios support in the features section, we will use it later 😉.

$ mkdir monorepo
$ cd monorepo
$ npx create-nuxt-app www

create-nuxt-app

We have our frontend application almost ready, we will need to add an API to our monorepo project, let’s create an api folder and add a Node.js microservice in there (no need to create the now.json, we will take care of that later).

Let’s create a bands microservice:

$ mkdir api
$ touch api/bands.js

api/bands.js

module.exports = (req, res) => {
const bands = [
{
name: 'Dio',
genre: 'Heavy Metal'
},
{
name: 'Anthrax',
genre: 'Trash Metal'
},
{
name: 'Tenebrarum',
genre: 'Gothic Metal'
}
]
res.end(JSON.stringify(bands))
}

yes, I like Metal 🤘

Let’s create a Deployment Configuration file to wire up our two project in the monorepo.

now.json

{
"version": 2,
"name": "monorepo",
"builds": [
{ "src": "www/package.json", "use": "@now/static-build" },
{ "src": "api/.js", "use": "@now/node" }
],
"routes": [
{ "src": "/api/(.
)", "dest": "/api/$1" },
{ "src": "/(.*)", "dest": "/www/$1" }
]
}

More information about how routes work in their documentation.

Here we are creating both the API and the Web project in one single repo using two different serverless applications, one served by @now/node and the other built by @now/static-build.

Before deploying let’s add the following to our www project:

  • Add a now-build script to the package.json file as following:
"now-build": "API_URL=https://monorepo.julianduque.now.sh npm run generate"

This will setup Axios to discover our API endpoint in the proper URL (make sure to use your alias here), and will tell now how to generate a static site for Nuxt.

  • Let’s update our pages/index.vue page to execute the Bands microservice we implemented with Node.js
export default {
components: {
Logo
},
data: function () {
return {
bands: []
}
},
methods: {
async loadBands () {
try {
this.bands = await this.$axios.$get('/api/bands.js')
} catch (err) {
console.error(err)
}
}
}
}

  • Add a Button to the <template> and render the items with Vue.js
<a v-on:click="loadBands">Load Bands</a>
<ul v-bind:key="band.name" v-for="band in bands">
<li>{{ band.name }} - {{ band.genre }}</li>
</ul>

And voila! We have connected our two serverless applications in one monorepo with Now!

Originally published by Julián Duque at https://dev.to

Learn More

☞ The Complete Node.js Developer Course (2nd Edition)

☞ Learn and Understand NodeJS

☞ Node JS: Advanced Concepts

☞ GraphQL: Learning GraphQL with Node.Js

☞ Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

☞ Beginner Full Stack Web Development: HTML, CSS, React & Node

☞ Node with React: Fullstack Web Development

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

Microservices in Node.js

Microservices in Node.js

In this article, we’re going to create a Microservice using Node.js which connects to an external API. A look at the basics of microservices, by way of a Lego-themed Node-based example.

Microservices are an architectural approach based on building an application as a collection of small services.

Let’s think of an application as a store. Applications are traditionally “monolithic” which means they are built as a single, autonomous unit --think of your favorite big-box store, selling everything from bananas to lawn furniture.

Everything is contained inside the unit. Let’s imagine that the person in this image - I’ll call him Jeff - is going inside the store to buy chewing gum and t-shirts. He can get a shopping cart to carry his purchases, look at products in different aisles, and pay at the checkstand before leaving--essentially, everything he needs is inside the store. These could also just as easily be components of an online Lego store application 👇.

All of this is run within a single process, and if our Lego store becomes very popular and we want to expand the business, we will have to add more Lego blocks in the same unit... and in the case of the online store, add more servers in order to scale it out.

So, every change (even minor changes) in our Lego store (physical or online) can be slow or tedious as it affects the entire system. In the case of Jeff’s store, a modification can require the removal or addition of multiple Lego blocks, affecting the entire structure. In the monolithic online store, a modification made to a small section of code might require building and deploying an entirely new version of software. So, scaling specific functions or components of the application, also means you have to scale the entire system.

Other problems with a monolithic approach in an online application are:

  • Inflexibility: it cannot be built using different technologies
  • Potentially unreliable: if even one feature of the system does not work, then the entire system does not work
  • Unscalable: applications cannot be scaled easily, since each time the application needs to be updated, the complete system has to be rebuilt
  • Not suitable for continuous development: many features of an application cannot be built and deployed at the same time
  • Slow development: As you can likely guess from the preceding points, development in monolithic applications takes a lot of time, since each feature has to be built individually, one after the other, rather than allowing multiple features to be worked on concurrently

This is where microservices come to the rescue!

Instead of containing everything in a single unit, the microservices-based application is broken down into smaller, lightweight pieces based on a logical construct. The application consists of independent small (micro-) services, and when we deploy or scale the app, individual services get distributed within a set of machines which we call “a cluster” in the service fabric world.

So in our Lego store example, perhaps one microservice contains a shopping cart, another one a product catalog, while another handles checkout, and so on. This approach allows developers to embrace compact and specialized tools that get each job done properly. Microservices are exactly that, scaled to enterprise level.

Each service has its own unique and well-defined role, runs in its own process, and communicates via HTTP APIs or messaging. Each microservice can be deployed, upgraded, scaled, and restarted independently of all the sibling services in the application. They are typically managed by an automated system, making it possible to deploy frequent updates to live applications without affecting the end-users.

Following this pattern, Jeff’s store will be very different: now he won’t have one big store where he can find everything he needs, but there would have multiple stores and each store will be independent and have specific functions. The first store may contain only Lego castles, another one bridges, and another one, Lego rockets

All of the Lego stores will be part of a “Lego shopping mall” or “cluster,” and if I want to expand, scale, upgrade, or modify only the store selling rockets, the castle store (and the rest) won’t be affected.

In other words, developers identify the separate service “pieces” that are logically closely related and necessary parts of a project. Then, they choose from the options available that meet their particular needs, from open source to enterprise solutions, and knit everything together into a functional application.

Advantages of using microservices:
  • Allows us to build, operate and manage services independently, and we can easily scale them out based on the resources they need.
  • Microservices take a lot of infrastructure risk out of the project straight away. With the infrastructure made almost invisible, microservice teams can iterate quickly.
  • Each developer on a team can avoid getting tangled up in the underlying infrastructure, and focus on their piece of the project. Then, in production, if individual project modules don’t work exactly right together, it’s easy enough to isolate, disassemble and reconfigure them until they do. If shoppers aren’t big fans of the mall’s specialty ketchup store, a shoe store can be built in its place. It offers better resource utilization and cost optimization
  • Microservices have their own load balancer and execution environment to execute their functionalities, and at the same time, capture data in their own databases.
  • Finally, microservices offer language and platform freedom, so teams can choose the best language for the job at hand (even if that’s .NET for one team and Node.js for another team).
Drawbacks of microservices:
  • Microservices are not automatically the right solution for every project. When you are running multiple instances of the same service or worker, you don’t necessarily need microservices. A well-built monolithic system can scale just as well for some classes of problems.
  • One of the big problems with microservices is “orchestration”, which means how to integrate the services with a guide to drive the process, much like a conductor in an orchestra. Integrating microservices can be quite complex.
  • Another complex process is “discovery” which is how applications and (micro)services locate each other on a network.
  • Moving away from a monolithic app architecture means the loss of an opinionated workflow that previously glued all the pieces together.
  • There is a risk in getting a very fragmented system where developers need to spend a lot of time and effort on gluing together services and tools, and where there’s a lack of common patterns and platforms that makes it difficult to work across different projects.
  • Microservices can also require increased testing complexity and possibly increased memory/computing resources.
  • It’s possible to create un-scalable microservices. It all comes down to how well you apply the fundamental principles. It’s all too easy to jump into shopping for all the microservices you want to apply without first truly considering the problem set you’re applying them to
Creating Microservices with Node.js

In this example, we’re going to create a microservice using Node.js which connects to an external API.

The requirement for this service is to accept two Zip Codes of two Lego stores and return the distance between them in miles.

Initial Steps
  1. Have Node.js installed
  2. Run npm init in the root folder for the project. This will create a package.json file that will prompt some questions about the package, if you are not sure how to answer you can use the default.
  3. We are going to use two packages, Express and Require that can be installed like this:
$ npm install express request --save

Let’s look at the structure of the folders. There are two files and a folder created by the npm init command. These are package.json, package-lock.json, and node_modules. When we installed the express and request packages, their dependencies were downloaded and saved in node_modules.

The primary file in our project is named server.js. And your package.json should look similar to this ☝️.

Then we create two folders, api for files that will support the API, and service for the logic to connect to a third-party API.

Let’s build our service!

Creating a Server to Accept Requests

Create a file in the root folder for your project called server.js which will be our primary file. This file contains the code below.

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

const routes = require('./api/routes');
routes(app);
app.listen(port, function() {
  console.log('Server started on port: ' + port);
});

This file is creating our server and assigns routes to process all requests.

We first require express into the file, and use it to create a new app object const app = express(); then we specify the port, in this case, we use the environment variable called PORT, and if the variable isn’t defined, it will use the default port: 3000.

Then we bring the routes object from the routes.js file in the api folder. We’ll pass the app to the routes object, and that sets the routes for our application. Finally, we’ll tell the app to start listening on the port we defined and to display a message to the console when this process is complete.

Defining the routes

The next step is to define the routes for the microservices and then assign each to a target in the controller object (that will control the flow of data in the application). We’ll build the controller in the next step. We’ll have two endpoints. One endpoint called “about” that returns information about the application. And a “distance” endpoint that includes two path parameters, both Zip Codes of the Lego store. This endpoint returns the distance, in miles, between these two Zip Codes.

'use strict';

const controller = require('./controller');

module.exports = function(app) {
  app.route('/about')
      .get(controller.about);
  app.route('/distance/:zipcode1/:zipcode2')
      .get(controller.getDistance);
};

The ‘use strict’ directive at the top of the file is used by new versions of Javascript to enforce secure coding practices. The first thing we’ll do is to create a controller object which we’ll define in the next step. Module.exports allows us to declare functions inside a module, and have them available for use in another file. This file constitutes the routes module, which we imported into our primary server.js file and used it to define the routes for our express app. This function adds two routes to the app. The first route listens for GET requests on the /about endpoint. These requests are handled by the about function in the controller. The second route listens for GET requests on the /distance endpoint. The getDistance function in the controller handles these requests. Two parameters are also specified. These are labeled zipcode1 and zipcode2 respectively. Let’s build the controller to handle those requests.

Adding Controller Logic

Within the controller file, we’re going to create a controller object with two properties. Those properties are the functions to handle the requests we defined in the routes module.

'use strict';

var properties = require('../package.json')
var distance = require('../service/distance');

var controllers = {
  about: function(req, res) {
      var aboutInfo = {
          name: properties.name,
          version: properties.version
      }
      res.json(aboutInfo);
  },
  getDistance: function(req, res) {
          distance.find(req, res, function(err, dist) {
              if (err)
                  res.send(err);
              res.json(dist);
          });
      },
};

module.exports = controllers;

We have two distinct parts to our controller. We’ll go through the code for the about functionality first. At the top, we create an object called properties which references the package.json file which npm created when it bootstrapped the project. This file is in JavaScript Object Notation or JSON for short. This format affords us the ability to import and use the information it contains.

Within the controllers object, we define a property called about. This property is a function which accepts request and response objects. We’ll only use the response object for this function. Using the name and version information from the package.json file, we’ll build a new object and return it as the response.

For the getDistance functionality, we’ll start by bringing in the distance module. We’ll pass the request and response objects to the find function within this module. This function also includes a callback function. This function accepts an error object (err) and a distance object (dist). If there is an error in the response, we return that with our response; otherwise, we send back the results of the find function.

Making the External Call

We’re ready for the final piece of the puzzle. This file handles the call to a third-party API. We’ll use the distance API provided by ZipCodeAPI.com. (You need an API key to use this, and it is free if you register. You can also use the key from the example if you want to test your service, but this key frequently expires during the day).

I set my key as an environment variable on my system and named it ZIPCODE_API_KEY. The default key in the code is an expired test key from the ZipCodeAPI website.

var request = require('request');

const apiKey = process.env.ZIPCODE_API_KEY || "hkCt1nW1wF1rppaEmoor7T9G4ta7R5wFSu8l1dokNz8y53gGZHDneWWVosbEYirC";
const
zipCodeURL = 'https://www.zipcodeapi.com/rest/';

var distance = {
  find: function(req, res, next) {
      request(zipCodeURL + apiKey
              + '/distance.json/' + req.params.zipcode1 + '/'
              + req.params.zipcode2 + '/mile',
      function (error, response, body) {
          if (!error && response.statusCode == 200) {
              response = JSON.parse(body);
              res.send(response);
          } else {
              console.log(response.statusCode + response.body);
              res.send({distance: -1});
          }
      });

  }
};

module.exports = distance;

We’re using the request package to execute the external HTTP request, and we already discussed the api Key above. Ensure that you update it unless you want to start by testing the error conditions.

The find function accepts request, response and next objects as parameters. The request object accepts the URL of the service we’re calling and then defines a callback function to handle the response.

If there are no errors, and the status of the response is HTTP Status code 200, then the function parses out the body of the response into an object called response and returns it on the resp object. Since the ZipCodeAPI returns with a JSON response, we could forward this directly. Parsing it out allows us the option of doing more with the response if we choose to.

We log failures to the console, and then a result of -1 is sent on the response object. You may opt to create an error object to return as well.

Finally, we export the distance object, which allows the controller to instantiate it and call its functions as needed.

Execution

Assuming there aren’t any typos, your application should be ready to execute. Open a console window and run the following command:

npm start

Assuming it starts correctly, and the port you define is 3000, you can now open your browser and navigate to:

http://localhost:3000/about when you will see the name of the app and the version.

Now if you add two parameters, the two zip codes, you will see something like this:

http://localhost:3000/distance/84010/97229

And that’s it! Using microservices to know the distance between two zip codes!

Conclusion

In microservices, every single service is independently deployable, scalable and updatable, this is what makes microservices such an appealing architectural approach to the industry.

A microservice is loosely coupled and interacts with other microservices for well-defined interfaces using protocols like http, they remain consistent and available in the presence of failure, meaning even if the machine goes down that host a microservice, the functionality provided by the service should still be offered by the application.

While microservices are great, there is quite some work involved to build a scalable microservice application on a platform as you need to consider things like cluster management, service orchestration, inter-service communication and so on, and you also need to put a lot of effort into following DevOpsbest practices.

Not to mention that microservices can also require increased testing complexity and possibly increased memory/computing resources. Thus, despite the abundant potential benefits, those knowledgeable in the field caution that microservices are not automatically the right solution for every project.

  • Lego is a registered trademark

Resources

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Microservices

An Introduction to Microservices

What is Microservices?

Build Spring Microservices and Dockerize Them for Production

Best Java Microservices Interview Questions In 2019

Build a microservices architecture with Spring Boot and Spring Cloud

Design patterns for microservices 🍂 🍂 🍂

Kotlin Microservices With Micronaut, Spring Cloud, and JPA

Build Spring Microservices and Dockerize Them for Production

Secure Service-to-Service Spring Microservices with HTTPS and OAuth 2.0

Build Secure Microservices with AWS Lambda and ASP.NET Core


Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Building Real-World Microservices with Node.js

Building Real-World Microservices with Node.js

This article is intended to be a quick-start guide for developing real-world Microservices with Node.js.

Originally published by Mike Mackrory at https://blog.cloud66.com

It’s the article that I would have liked to read when I started programming with Node.js. Therefore, you won’t find the words “Hello” or “World” anywhere in this article (at least, not more than that first mention). You should have a basic understanding of Javascript, but other than that, follow the steps for a working application.

In our highly connected world, projects can be constructed by combining functionality from different APIs in unique and performant ways. In this example, we’re going to create a Microservice using Node.js which connects to an external API, and then look at improvements we can make to make it more cost-effective and performant.

The business requirement for this service is to accept two Zip Codes and return the distance between them in miles. We’ll look at validation techniques, the configuration for an external API call, and implement an internal cache to make duplicate calls faster and more cost-efficient.

Initial Steps

You’ll need to have Node.js installed on your workstation for this example. I’m using version 8.11, and you can download the latest version for your operating system from Nodejs.org. The Node.js installation includes NPM, which is the Node.js package manager. We’ll use NPM to bootstrap the project, install dependencies and execute the service. (You can follow along with this example or view the completed example in this GitHub repository.)

We’ll start by initializing the project using npm init. Run this command in the root folder for the project. The command walks you through the creation of the package.json file, which is the foundation for the project. If you’re not sure of an answer, accept the default, and we can update it later if necessary. We’ll be using the name and version a little later.

$ npm init 

We’re going to use a package called Express to build our service. Express is an established framework for Node applications and continues to benefit from the support of the Node.js Foundation. We’re also going to use the Request package to enable us to connect with a third-party API on the Web.

We’ll add these packages to our project with the following command (the save flag at the end of the command adds it to the package.json file which was created by NPM).

$ npm install express request --save 

One last thing before we delve into the code. Let’s look at the structure of how it’s all going to fit together. There are two files and a folder created by the npm init command. These are package.json, package-lock.json, and node_modules. When we installed the express and request packages, their dependencies were downloaded and saved in node_modules.


The primary file in our project is named server.js. We’ll have files to support the API in a folder called api, and we’ll add the logic to connect to a third-party API in the service folder.

Let’s build our service!

Creating a Server to Accept Requests

We’ll start from our primary file, then define the routes, add controllers, and finally, build the connection to an external service.

Create a file in the root folder for your project called server.js. This file contains the code below. I’ll step through each part of it, so you can see how it goes together.

var express = require('express')
var app = express();
var port = process.env.PORT || 3000;

var routes = require('./api/routes');
routes(app);
app.listen(port, function() {
  console.log('Server started on port: ' + port);
});

This file creates our server and assigns routes to process all requests. We’re going to have two endpoints which we’ll define in the next step.

The first thing we’ll do is to bring the express package into the file. We’ll use this to create a new app object. We’ll also specify the port. The process object is used to reference system properties. If I want to define the port number based on the machine running the application, I can define an environment variable called PORT, and it will be used. The default port value is 3000 if it isn’t defined.

The next line brings in a routes object from the routes.js file in the api folder. We’ll pass the app to this object, and that sets the routes for our application. Finally, we’ll tell the app to start listening on the port we defined, and to display a message to the console when this process is complete.

Defining the Routes

The next step is to define the routes for the server and assign each to a target in our controller object. We’ll build the controller in the next step. We’ll have two endpoints. An about endpoint returns information about the application. A distance endpoint includes two path parameters, both Zip Codes. This endpoint returns the distance, in miles, between these two Zip Codes.

'use strict';

var controller = require('./controller');

module.exports = function(app) {
  app.route('/about')
      .get(controller.about);
  app.route('/distance/:zipcode1/:zipcode2')
      .get(controller.get_distance);
};

The ‘use strict’ directive at the top of the file is used by new versions of Javascript to enforce secure coding practices. The first thing we’ll do is to create a controller object which we’ll define in the next step. Because we declare this outside of any functions in the file, it is accessible by all of them.

Module.exports allows us to declare functions inside a module, and have them available for use in another file. This file constitutes the routes module, which we imported into our primary server.js file and used it to define the routes for our express app.

This function adds two routes to the app. The first route listens for GET requests on the /about endpoint. These requests are handled by the about function in the controller. The second route listens for GET requests on the /distance endpoint. The get_distance function in the controller handles these requests. Two parameters are also specified. These are labeled zipcode1 and zipcode2 respectively.

Let’s build the controller to handle those requests.

Adding Controller Logic

One of the aspects of Javascript and Node.js which I find interesting is that functions are objects. Within the controller file, we’re going to create a controller object with two properties. Those properties are the functions to handle the requests we defined in the routes module.

'use strict';

var properties = require('../package.json')
var distance = require('../service/distance');

var controllers = {
  about: function(req, res) {
      var aboutInfo = {
          name: properties.name,
          version: properties.version
      }
      res.json(aboutInfo);
  },
  get_distance: function(req, res) {
          distance.find(req, res, function(err, dist) {
              if (err)
                  res.send(err);
              res.json(dist);
          });
      },
};

module.exports = controllers;

We have two distinct parts to our controller. We’ll go through the code for the about functionality first. At the top, we create an object called properties which references the package.json file which NPM created when it bootstrapped the project. This file is in JavaScript Object Notation or JSON for short. This format affords us the ability to import and use the information it contains.

Within the controllers object, we define a property called about. This property is a function which accepts request and response objects. We’ll only use the response object for this function. Using the name and version information from the package.json file, we’ll build a new object and return it as the response.

For the get_distance functionality, we’ll start by bringing in the distance module. We’ll pass the request and response objects to the find function within this module. This function also includes a callback function. This function accepts an error object (err) and a distance object (dist). If there is an error in the response, we return that with our response; otherwise, we send back the results of the find function.

Making the External Call

We’re ready for the final piece of the puzzle. This file handles the call to a third-party API. We’ll use the distance API provided by ZipCodeAPI.com. (You need an API key to use this, and it is free if you register. You can also use the key from the example if you want to test your service, but this key frequently expires during the day.)

I set my key as an environment variable on my system and named it ZIPCODE_API_KEY. The default key in the code is an expired test key from the ZipCodeAPI website.

var request = require('request');

const apiKey = process.env.ZIPCODE_API_KEY || "hkCt1nW1wF1rppaEmoor7T9G4ta7R5wFSu8l1dokNz8y53gGZHDneWWVosbEYirC";
const zipCodeURL = 'https://www.zipcodeapi.com/rest/';

var distance = {
  find: function(req, res, next) {
      request(zipCodeURL + apiKey
               + '/distance.json/' + req.params.zipcode1 + '/'
               + req.params.zipcode2 + '/mile',
      function (error, response, body) {
          if (!error && response.statusCode == 200) {
              response = JSON.parse(body);
              res.send(response);
          } else {
              console.log(response.statusCode + response.body);
              res.send({distance: -1});
          }
      });

  }
};

module.exports = distance;

We’re using the request package to execute the external HTTP request, and we already discussed the api Key above. Ensure that you update it unless you want to start by testing the error conditions.

The find function accepts request, response and next objects as parameters. The request object accepts the URL of the service we’re calling and then defines a callback function to handle the response.

If there are no errors, and the status of the response is HTTP Status code 200, then the function parses out the body of the response into an object called response and returns it on the resp object. Since the ZipCodeAPI returns with a JSON response, we could forward this directly. Parsing it out allows us the option of doing more with the response if we choose to.

We log failures to the console, and then a result of -1 is sent on the response object. You may opt to create an error object to return as well.

Finally, we export the distance object, which allows the controller to instantiate it and call its functions as needed.

Execution and Debugging

Assuming there aren’t any typos, your application should be ready to execute. Open a console window and run the following commands—The first ensures that all the packages used by the application are downloaded and up-to-date:

$ npm install

The second command starts your application.

$ npm start

Assuming it starts correctly, and the port you define is 3000, you can now open your browser and navigate to:

http://localhost:3000/about

http://localhost:3000/distance/84010/97229

The following URL allows you to see the error condition because 92001 is not a recognized Zip Code.

http://localhost:3000/distance/84010/92001

If you run into problems, I’ve found the error messages to generally be helpful in pointing me to the line of code with the offending syntax, missing punctuation, or other problems. The Internet is also a wealth of information for specific problems.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

Node.js 12: The future of server-side JavaScript

An Introduction to Node.js Design Patterns

Basic Server Side Rendering with Vue.js and Express

An Introduction to Microservices

What is Microservices?

Build Spring Microservices and Dockerize Them for Production

Best Java Microservices Interview Questions In 2019

Build a microservices architecture with Spring Boot and Spring Cloud