【问题标题】:NodeJS GET request not working with AngularJSNodeJS GET请求不适用于AngularJS
【发布时间】:2016-04-20 14:03:16
【问题描述】:

我有这个用于分享照片的网络应用程序。

现在我有了这条路线,它应该从以下数组中返回所有用户的照片。

路线:

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

});

我发现 req.body.following 是未定义的。这就是我使用 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;
    });
    }
}

为什么会发生这种情况以及如何解决?

谢谢!

【问题讨论】:

    标签: javascript angularjs node.js express


    【解决方案1】:

    不确定服务器端,但我在 Angular 代码中发现了两个问题。执行HTTP GET 请求时不能传递正文。尝试通过 url 传递任何必要的数据。

    此外,返回的实际数据将在response.data 中。做这样的事情:

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

    要构建 urlData,请查看this 问题。

    当然,您必须调整服务器,使其从 url 读取数据,而不是从正文中读取数据。

    【讨论】:

    • 就是这样。非常感谢! :)
    【解决方案2】:

    我不知道请求请求头中的 Content-Type 是什么 application/jsonapplication/x-www-form-urlencoded 或其他。每种内容类型都必须区别对待。如果你使用 expressjs,尝试使用multer 处理具有multipart-form 内容类型的请求,我通常在我的应用程序中使用它。

    【讨论】:

      【解决方案3】:

      $http 不接受 GET 方法中数据对象的第二个参数。但是,$http 确实接受一个数据对象作为 POST 方法中的第二个参数。

      您需要将它作为配置对象的 params 属性传递并在节点的 req.query 中访问它:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-12
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 2019-04-11
        • 2020-07-19
        • 2020-07-07
        • 1970-01-01
        相关资源
        最近更新 更多