Calling Externally Hosted Service using Node.js

Posted by: Mahesh Sabnis , on 2/17/2016, in Category Node.js
Views: 66528
Abstract: In Node.js using http module’s request object we can call an external service.

In a project, there could be a possibility that our Node.js application needs to connect with other existing applications to fetch data.

Considering this, we need to build a Node.js based application which can read and post data from and to the vendor application. In this case, we need to make use of node’s http module to create a request object. This module provides facility to create http server for handling request processing from the Node.js client and is also used to generate request for the external server. Check out this link to create a Web Server using Node.js. The following diagram explains the scenario for external Communication from a Node.js application.

 

nodejs-external-communication

The above diagram explains a scenario of a Node.js application communicating with an external service. The external vendor application may be hosted on On-Premises Server or Cloud Server. The http module defines the request object using which the communication can be established.

While implementing the external service communication, we need the following information about the service:

1. Host Name or IP Address - The physical host information to make a call.

2. The URL PATH of the service - The URL path of the service to be subscribed by the http request object to make a call.

3. PORT on which service is listening

4. Method for defining the request type, GET, POST, PUT and DELETE.

5. Headers, this is very important when the POST, PUT request are made. This contains the information such as Content-Type, Content-Length.

Node.js Application connecting to an external service

The following application is implemented using Visual Studio Code (hence further referred to as VSCode). This is a  free IDE by Microsoft for developing Node.js, ASP.NET, C# apps. This is available on Windows, Linux and Mac OSX Platform. This can be downloaded from https://code.visualstudio.com/. Alternatively, Visual Studio 2013 or 2015 can also be used with Node.js tools from this link.

You can use any free REST API service for our example. However in this demo, our Node application uses a sample Web API which is shipped with ASP.NET MVC 4. Please read about how to create a Web API. Also note that the article uses the Web API service performing READ/WRITE operations for EmployeeInfo with properties as

  • · EmpNo
  • · EmpName
  • · Salary
  • · DeptName
  • · Designation.

If you are going ahead with a free REST API, please test them using fiddler tool or Postman tool and then make the necessary code changes. Along with the code of this article, the code for Web API can also can be downloaded.

Step 1: Create folder on your Hard Drive of name NODE_CONNECT_EXTERNALSERVER. Open VSCode, open the created folder using File->Open Folder option. In this folder add a new file of name app.js.

Step 2: To use the Node.js intellisense for the application, right click on app.js and select option, Open in Command Prompt….. This will open the command prompt, from this command prompt, run following commands:

npm install -g tsd

This will install Type Script definition for VSCode.

tsd query node --action install

This will install Node.js intellisense for the current application and will provide an easy access of all the Module object in the application.

 

Step 3: In the app.js add the following code:

//1.
var http = require('http');

var emp = [];

//2.
var extServerOptions = {
    host: 'localhost',
    port: '3752',
    path: '/api/EmployeeInfoAPI',
    method: 'GET'
};
//3.
function get() {
    http.request(extServerOptions, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (data) {
            emp = JSON.parse(data);
            emp.foreach(function (e) {
                console.log(e.EmpNo + "\t" + e.EmpName + "\t" + e.Salary + "\t" + e.DeptName + "\t" + e.Designation);
            });
        });

    }).end();
};

get();

console.log("Doing the Post Operations....");
//4
var employee = JSON.stringify({
    'EmpName': 'VB',
    'Salary': 52000,
    'DeptName': 'HR',
    'Designation': 'LEAD'
});


//5
var extServerOptionsPost = {
    host: 'localhost',
    port: '3752',
    path: '/api/EmployeeInfoAPI',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Employee.length
    }
};



//6
var reqPost = http.request(extServerOptionsPost, function (res) {
    console.log("response statusCode: ", res.statusCode);
    res.on('data', function (data) {
        console.log('Posting Result:\n');
        process.stdout.write(data);
        console.log('\n\nPOST Operation Completed');
    });
});

// 7
reqPost.write(employee);
reqPost.end();
reqPost.on('error', function (e) {
    console.error(e);
});

get();

The above code has the following specifications:

1. Loads the http module for defining request object.

2. The extServerOptions JavaScript object defines the external server information like Host, Port, path, method, etc.

3. The get () function is used to make http request to the external server. request () is a function that accepts extServerOptions object as first parameter and the second parameter is the callback. This will complete the call to the external server and read the data received on the event. The data is stored in the emp array object and then printed on console.

4. Define an Employee object with properties and values. This object will be used for POST request.

5. The extServerOptionsPost object defines the external server information like explained in step 2. This has additional parameter headers. This parameter is mandatory for the request object. This will inform the request object about the format of the data to be posted to the external server.

6. This step along with step 7 defines the request object for posting data to the external server based on the information defined in Step 5. The callback passed to the request object monitors data to be posted. Step 7 writes data with the request object.

Step 4: To run the application, make sure that the REST Service / WebAPI is running. Right click on app.js and select option of Open in Command Prompt. On the command prompt, run the following command

node app

The following result will be displayed

nodejs-calling-service

In the above image, the red vertical line shows the final data received from the server and the red rectangle shows the data posted to the server.

Conclusion

In Node.js using http module’s request object we can perform data read/write operations with an external service or application.

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!