QuikProBroNa QuikProBroNa - 7 months ago 32
Javascript Question

NodeJS GET request not working with AngularJS

I have this web app that is for sharing photos.

Now I have this route that is supposed to return the photos of all the users from the following array.

Route:

router.get('/getphotos',function(req, res){
var reqPhotos = [];
console.log( "\n" + req.body.username + "\n");
try{
for(x =0; x < req.body.following.length; x++){
reqPhotos.push({username: req.body.following[x].username});
}
}
catch(err){
console.log(err);
}

Photo.find({username: reqPhotos}).exec(function(err, allPhotos){
if(err){console.log(err);}
else{
res.json(allPhotos);
}
});

});


I have found out that the req.body.following was undefined. This is how I was calling it using angular:

$scope.getPhotos = function(){

if($scope.identification){
flng = angular.copy($scope.identification.following);
flng.push($scope.identification.username);
var data = {username: $scope.identification.username, token: $scope.identification.token, following: flng}
//IDENTIFICATION HAS ALL THE INFO.
$http.get('/users/getphotos', data).success(function(response){
$scope.photos = response;
});
}
}


Why does this happen and how to fix it?

Thanks!

Answer

Not sure about the server side, but I see two problems in the angular code. You cannot pass a body when doing an HTTP GET request. Try to pass any necessary data through the url.

Also, the actual data that is returned, will be in response.data. Do something like this:

var urlData = ""; //add any url data here, by converting 'data' into url params
$http.get('/users/getphotos/' + urlData).then(function(response){
    $scope.photos = response.data;
});

For constructing the urlData, have a look at this question.

Of course, you will have to adjust the server so it reads the data from the url, rather than from the body.

Comments