【问题标题】:Angularjs $http returns error 0Angularjs $http 返回错误 0
【发布时间】:2013-10-21 20:40:05
【问题描述】:

好的,所以我有一个以 Laravel 4 作为后端的 AngularJS 应用程序。我想要开发的方式是在单独的服务器上运行 Laravel(通过 artisan serve),并在单独的服务器上运行 angular,让 yeoman 为我组装所有的 grunt 服务器。

但是,在尝试通过 Angulars $http 从 Laravel 4 后端(用作 REST api)获取数据后,我得到的只是一条 0 错误消息。这是我的代码:

Angular REST 服务:

app.factory('RestService', function($http){
   var restUrl = 'http://localhost:8000/api/v1/tags';//<-- rest api served with php artisan

   return {
      getResource: function(){
      return $http({method: 'get', url: restUrl})
      }
   }
});

角度控制器:

app.controller('TagCtrl', function($scope, RestService){
   $scope.getTagList = RestService.getResource()
      .success(function(){
         console.log('Success!');
      })
      .error(function(data, status, headers, config){
         console.log(data);//<--returns nothing
         console.log(status);//<--returns 0
         console.log(headers);//<-- returns function
         console.log(config);//<-- returns object
     });

});

这是我的 Laravel 4 路线:

Route::get('tags', function(){

      return "This is a temporary message to test routing";

   });

现在,如果我不使用 grunt serve 和 artisan 并将它们全部放在同一个文件夹中(laravels 公用文件夹中的 angular 等),那么所有这些都可以工作,我打算在进入生产环境时这样做,但因为我想缩小并用 grunt 做其他事情,在此之前我想暂时将这些元素分开。

通过谷歌搜索,我认为问题出在 CORS(跨源请求)上,但我不明白如何解决此设置中的问题。

【问题讨论】:

  • 使用开发者工具在 Chrome 中运行它。如果您的脚本客户端/api 在本地主机上,则 CORS 没有问题。

标签: javascript php angularjs laravel


【解决方案1】:

试试这个:

        $scope.url = 'http://localhost:8000/api/v1/tags';
        $scope.content = [];

        $scope.fetchContent = function() 
        {
            $http.get($scope.url).then(function(result)
            {
                $scope.content = result.data;
            });
        }

        $scope.fetchContent();

还可以尝试返回一个数据数组。 + 也返回一个响应代码。例如:

return Response::json(array(
    'message' => 'This is a temporary message to test routing'), 200);

【讨论】:

    【解决方案2】:

    尝试在您的工厂声明中添加 $http 服务:

    app.factory('RestService', function($http){
    

    【讨论】:

    • 很抱歉,缺少 $http 是一个错字。它在实际代码中。
    猜你喜欢
    • 2015-01-24
    • 2018-07-07
    • 2015-01-12
    • 2017-05-13
    • 2017-09-24
    • 2014-08-12
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多