Beginners Guide to Building Real-World Microservices with Node.js

Initial Steps

$ npm init
$ npm install express request --save

Creating a Server to Accept Requests

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); });

Defining the Routes

'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); };

Adding Controller Logic

'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;

Making the External Call

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;

Execution and Debugging

$ npm install
$ npm start

Related Content:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store