2013-10-14 114 views
0

好吧,我有一個以Laravel 4作爲後端的AngularJS應用程序。我想要開發的方式是通過在單獨的服務器上運行Laravel(通過工匠服務),以及與yeoman爲我組裝所有grunt服務器的單獨角色。

但是,當試圖通過Angulars $ http從Laravel 4後端(作爲REST API)獲取數據後,我得到的是0錯誤消息。這裏是我的代碼:

角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"; 

    }); 

現在,當這一切工作,如果我不使用咕嚕服務和工匠,並把它放在同一個文件夾(在laravels公共文件夾等角度)當我轉向生產時我打算做這些工作,但是因爲我想在這之前先咕嚕咕嚕地做其他事情,所以現在我想讓這些元素保持獨立。

隨着一些谷歌搜索我認爲問題是與CORS(交叉來源請求),但我不明白如何解決在這種設置問題。

+0

使用開發人員工具在Chrome中運行它。如果你的腳本client/api在localhost上,那麼CORS就沒有問題。 – Whisher

回答

0

嘗試在你的工廠聲明添加$ http服務:

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

抱歉缺少$ http是一個錯字。它在實際的代碼中。 – Tomkarho

0

試試這個:

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