Wednesday, January 3, 2018

NodeJS httpServer make REST calls based on querystring parameter

Has dependencies on request, which you could install using the npm command.
In the example below it is a simple web application listening on localhost port 8080.
If the employeeId querystring parameter is detected, regardless of the path, it will make a call to a  RESTful service to retrieve a (fictional) worker information... you get the idea.

 // Include the request library for Node.js. This is not part of native libary.    
 var request = require('request');  
 var http = require('http');  
 var url = require('url');  
 http.createServer(function (req, res) {  
   res.writeHead(200, {'Content-Type': 'text/html'});  
      res.write('Start querying<br />');  
      var u = url.parse(req.url, true);  
      var queryData = u.query;  
      if (queryData.employeeId) {  
           console.log('employeeId: ' + queryData.employeeId);  
           // Sample URL call: http://localhost:8080/anything?employeeId=999  
           // Basic Authentication credentials    
           var username = "username";   
           var password = "password";  
           var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");  
           request.get(    
           {  
                uri : "https://service.domain.com/WorkerSnapshot?$format=JSONP&EmployeeID=" + queryData.wwid,  
                rejectUnauthorized: false,  
                json: true, // indicates the returning data is JSON, no need for JSON.parse()  
                headers : { "Authorization" : authenticationHeader }   
           },  
           function (error, response, body) {  
                res.write(body);  
           }  
           );            
      }  
 }).listen(8080);  

3 comments:

goformule said...

very nice & informative video for mulesoft folks...you can also visit https://www.goformule.com for mulesoft tutorials

Anonymous said...

Hire Nodejs Developers for your blazing fast and secure web and mobile application development.

Veera Blogspot said...

ServiceNow Online Training

Related Posts Plugin for WordPress, Blogger...