Lijin Durairaj
Lijin Durairaj

Reputation: 3511

How to Fetch data from webAPi using nodeJS libraries?

I am new to nodeJS, i want to fetch data from webApi using nodeJS, for instance, when i make a call to the

mydomain/getAllStudents

i want all the students data and when i do

mydomain/student/4

then i want only the data of the student with the ID=2

-challenge-

using express i can specify the route like this

var app=express();
app.get('/getAllStudents',(request,response)=>{    
console.log('we are listening !!!');
}).listen(8080);

but when i try to make a call inside the callback function, i not able to get the value, my complete code

var http=require('http');
var express=require('express');

var app=express();

 var options={host: '172.17.144.6',
  port: 8394,
  path: '/api/Masterdata/getAllStudents',
  method: 'GET'}

app.get('/getAllStudents',(request,response)=>{

http.get(options,(res)=>{
res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});
console.log('we are listening !!!');
}).listen(8080);

what i am trying to achieve is, when i hit mydomain/getAllStudents i want to get all the data. how can i do this with nodeJS? can i do this with nodeJS statisfying my requirement?

Upvotes: 1

Views: 308

Answers (1)

Sadok Mtir
Sadok Mtir

Reputation: 615

So basically you want to expose the data through express after parsing them from another API. You can do like this:

To make the call from node js you can use this library: node-rest-client

var Client = require('node-rest-client').Client;
var remoteURL = "172.17.144.6:8394/api/Masterdata/getAllStudents";

var express = require('express');
var students = express.Router();
students.route('/getAllStudents')
 .get(function(req, res) {
    client.get(remoteURL, function (data, response) {
     console.log(data);
    if(response.statusCode === 200)
      res.status(200).send(data);
    });
});

Upvotes: 2

Related Questions