QuikProBroNa
QuikProBroNa

Reputation: 816

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!

Upvotes: 2

Views: 441

Answers (3)

Jun Duan
Jun Duan

Reputation: 218

$http doesn't take a 2nd parameter for a data object in GET method. However, $http does accept a data object as the 2nd parameter in POST method.

You'll need pass it as the params property of the config object and access it in your req.query in node:

$http.get('enter/your/url/', { params: data})

Upvotes: 1

fikkatra
fikkatra

Reputation: 5792

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.

Upvotes: 5

ysf
ysf

Reputation: 53

I don't know what the Content-Type in request request header, is that application/json or application/x-www-form-urlencoded or other. Every content type have to be treated differently. If you use expressjs, try using multer to handle request with multipart-form content type, I usually use it in my application.

Upvotes: 3

Related Questions