Search This Blog

Saturday, April 21, 2018

How to post data from angular to nodejs backend and parse response

Make the request in angular


app.js code , client side in our case.


$scope.getTor = function(){ // getTor is bound with ng-click in my html with my controller which has this method.

var torMcItems=$http({ // i want response in this variable.

method: 'GET',

url:'/api/tor' // my backend in server.js

})

.success(function(response){


response = JSON.parse(response);


torItemms=response.items;

}).error(function(err){


}

);

};


///////////////////////////////////////////////////////////

Now server side of the nodejs app , the below method is in server.js.


app.get('/api/tor', function(req, res){ //handle which was called in app.js

var request = require('request');

var options = {

url: 'https://theoldreader.com/reader/api/0/stream/contents?output=json&s=user/-/label/mcrecos',

headers: {

'Authorization':'GoogleLogin auth=emxxxxxxxC'

}

};

let body = [];

request(options).on('data', function(data)

{

//console.log(data.toString());

body.push(data);

}).on('end', function(){


body = Buffer.concat(body).toString();

res.setHeader('Content-Type', 'application/json');

res.write(JSON.stringify(body));

// want to convert the body to string , we will make it json object in the app.js using  JSON.parse

res.end();

});

} );

No comments:

Post a Comment