gpt4 book ai didi

javascript - AngularJS 没有得到 API 响应

转载 作者:行者123 更新时间:2023-12-01 04:10:04 25 4
gpt4 key购买 nike

使用 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 Controller

        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.";
});

AngularJS Display Code

<div ng-controller="HttpController">
The response is {{ testString }}<br>
{{validationString}}

在 AngularJS HTML 页面上显示

连接时显示KARAF日志

2017-01-10 11:42:30,133 |信息| qtp84694963-897 |登录拦截器 | 107 - org.apache.cxf.cxf-core - 3.2.0.SNAPSHOT |入站消息

ID:20地址: localhost:8181/cxf/strsoftware/testHttp 方法:GET内容类型:

header :{Accept=[application/json, text/plain, /], Accept-encoding=[gzip, deflate, sdch, br], Accept-Language=[en-US, en;q=0.8],连接=[保持事件],Content-Type=[null],主机=[localhost:8181],Origin=[localhost:63343],Referer=[localhost:63343/STRFrontEnd/StartScreen。 html?_ijt=qsu1c8a1qskj0def9ho1rml4hv], User-Agent=[Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,如 Gecko) Chrome/55.0.2883.87 Safari/537.36]}

2017-01-10 11:42:30,135 |信息| qtp84694963-897 | LoggingOutInterceptor | 登录拦截器107 - org.apache.cxf.cxf-core - 3.2.0.SNAPSHOT |出站消息

ID:20响应代码:200内容类型:application/json header :{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。仅以下协议(protocol)方案支持跨源请求:http、data、chrome、chrome-extension、https、chrome-extension-resource。

这是一个服务器端错误,因此我们目前正在服务器端实现 CORS,看看是否可以解决问题。找到解决方案后将发布解决方案。

最佳答案

尝试这个,如果不起作用将数据:''替换为参数:{}:

        $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 时,我们在浏览器中收到跨区域错误。

关于javascript - AngularJS 没有得到 API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41574275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com