DotNetCurry Logo

Calling Externally Hosted Service using Node.js

Posted by: Mahesh Sabnis , on 2/17/2016, in Category Node.js
Views: 22875
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)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years 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). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




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