好吧,所以我有一个以Laravel 4作为后端的AngularJS应用程序。 我想要开发的方式是在单独的服务器上运行 Laravel(通过工匠服务),并在单独的服务器上运行 yeoman 为我组装所有咕噜咕噜的服务器。
但是,在尝试通过 Angular 从 Laravel 4 后端(用作 REST api)获取数据后$http我得到的只是一条 0 错误消息。 这是我的代码:
角度休息服务:
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 公共文件夹内的角度等),那么所有这些都有效,我打算在转向生产时这样做,但因为我想缩小并做其他事情之前与 grunt 我想暂时将这些元素分开。
通过一些谷歌搜索,我认为问题出在 CORS(跨源请求)上,但我无法理解如何在此设置中解决问题。
尝试在工厂声明中添加$http服务:
app.factory('RestService', function($http){
试试这个:
$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);