2

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!

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
QuikProBroNa
  • 796
  • 2
  • 7
  • 25

3 Answers3

5

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.

Community
  • 1
  • 1
fikkatra
  • 5,605
  • 4
  • 40
  • 66
3

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.

ysf
  • 33
  • 1
  • 5
1

$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})

Jun Duan
  • 218
  • 1
  • 9