我正在尝试创建轻型Angularjs应用。我通过irb cli运行api服务器并且它在端口4567上运行。当我运行bundle exec ruby.rb时,我可以确认地址上有数据:http://localhost:4567/api/v1/companies:
[
{"id": "1",
"name": "A"
},
{
"id": "2",
"name": "B",
}
]
我尝试过这段代码(hello.js):
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.company=[];
$http.get("http://localhost:4567/api/v1/companies")
/*$http.get("http://localhost/fake.json")*/
.then(function(response) {
$scope.company = response.data;
});
});
HTML:
<html>
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in company">
{{ 'name: ' + x.name + ', id:' + x.id }}
</li>
</ul>
</div>
</body>
</html>
问题是,如果我将网址更改为&#34; http://localhost/fake.json&#34;如评论我看到数据响应清晰。但如果我使用本地Web服务器,我什么都看不到。是否存在某种权限问题或其他问题。
答案 0 :(得分:0)
使用success
回调代替then
,请参阅此document
$scope.company=[];
$http.get("http://localhost:4567/api/v1/companies")
/*$http.get("http://localhost/fake.json")*/
.success(function(response) {
$scope.company = response.data;// response or response.data is depend your service response
}).error(function(errorStatus)
{
//code
});
答案 1 :(得分:0)
问题是sinatra-access-control-allow-origin,我找到了解决方案:Sinatra access-control-allow-origin for sinatra public folder