![](/img/trans.png)
[英]AngularJS - API Call in a Loop - getting the max value of an array and setting a response
[英]AngularJS not getting API Response
我正在嘗試使用AngularJS和在OSGi環境(KARAF)中運行的CXF-JAXRS庫,來嘗試運行一個簡單的API響應。
日志顯示AngularJS已正確連接到REST服務,並且已正確響應200狀態代碼。 但是,在AngularJS中,不會檢索回發的信息。
僅供參考:我必須從所有鏈接中刪除“ http://”,因為StackExchange告訴我我沒有足夠的聲譽來包含它們。 但是它們在實際的代碼/日志中。
我正在連接的REST方法
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public Response test(){
String testResponse = "Success.";
Response responseString = Response
.status(200)
.entity(testResponse)
.build();
return responseString;
}
AngularJS控制器
app.controller('HttpController', function($scope, $http){
$http({
method: 'GET',
url: 'localhost:8181/cxf/strsoftware/test'
}).then(function successCallback(response){
$scope.testString = response.data;
}, function errorCallback(response){
$scope.testString = response;
});
$scope.validationString = "Controller is functional.";
});
<div ng-controller="HttpController">
The response is {{ testString }}<br>
{{validationString}}
在AngularJS HTML頁面上顯示
連接時顯示KARAF日志
ID:20地址:localhost:8181 / cxf / strsoftware / test HTTP方法:GET內容類型:
ID:20響應代碼:200內容類型:application / json標頭:{Content-Type = [application / json],Date = [Tue,2017年1月10日16:42:30 GMT]}
更新
通過在Chrome(Ctrl + Shift + I)上打開“檢查”頁面並單擊“控制台”,我們發現了以下錯誤:
angular.js:11756XMLHttpRequest無法加載localhost:8181 / cxf / strsoftware / test。 跨源請求僅支持以下協議方案:http,數據,chrome,chrome擴展名,https,chrome-extension-resource。
這是服務器端錯誤,因此我們目前正在服務器端中實施CORS,以查看是否可以解決問題。 找到后將發布解決方案。
您正在.then()中調用匿名函數。 所以應該是這樣的:
$http({
method: 'GET',
url: 'localhost:8181/cxf/strsoftware/test'
}).then(function(response){
$scope.testString = response.data;
}, function(response){
$scope.testString = response;
});
如果無法正常工作,請嘗試使用此命令:用params:{} 替換data ::
$http({
method: 'GET',
url: 'localhost:8181/cxf/strsoftware/test',
// Just to be sure! maybe you don't need it
dataType: 'json',
headers: {
"Content-Type": "application/json"
},
//To be sure Angular does NOT remove the content-type header.
data: '',
}).then(function successCallback(response) {
$scope.testString = response.data;
}, function errorCallback(response) {
$scope.testString = response;
});
編輯
查看此答案下面的評論,以了解Shadmehr在哪里解決了問題。 解決方案是在應用程序的服務器端部分實現CORS篩選器。 嘗試訪問API時,瀏覽器中出現跨區域錯誤。
不知道您的js代碼是否正確。 我還嘗試了angular js,我的代碼如下所示:
$http.get("/cxf/strsoftware/test")
.success(function (response) {$scope.testString = response.data;});
有關我的完整代碼,請參見blueprint-cdi-example 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.