gpt4 book ai didi

json - Angular JS - HTTP GET 请求抛出错误

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:28:29 25 4
gpt4 key购买 nike

我对 Angular JS 和 Ionic 应用程序还很陌生。我试图从 url 获取 json 数据。但是,不幸的是我没有得到任何回应。相反,我收到如下屏幕所示的错误

我试过两种方式,

尝试 1:

 function(){
return $http.get("url?subjStudyId=441",{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}).then(function(response){

chats = response.data;
alert(JSON.stringify(chats));
return chats;

},function(err) {
alert(JSON.stringify(err));
})
}

尝试 2:

function($http) {
var chats = [];
return {
all: function(){
return $http.get("url?subjStudyId=441").then(function(response){

chats = response.data;
alert(JSON.stringify(chats));
return chats;

},function(err) {
alert(JSON.stringify(err));
})
}
}

请帮我找到解决方案。

最佳答案

您的问题可能是 CORS,它代表 Cross-Origin Resource Sharing 看看这篇深入的 CORS 文章 here .

在您的后端启用 CORS 并再次尝试发出请求。您还可以通过在后端启用 JSONP 然后执行

$http.jsonp('url?callback=JSON_CALLBACK&param=value);

JSONP stands for "JSON with Padding" (and JSON stands for JavaScript Object Notation), is a way to get data from another domain that bypasses CORS (Cross Origin Resource Sharing) rules. CORS is a set of "rules," about transferring data between sites that have a different domain name from the client.

我编写了两个示例,一个使用 $http.get,另一个使用 $http.jsonp,这两个都告诉我你没有 >Access-Control-Allow-Origin "*" 在您的服务器中,您也没有 JSONP 支持设置。前往 enable-cors.org ,他们有很好的文章可以帮助您在后端设置 CORS。

从技术上讲,您应该坚持使用 CORS,因为 JSONP 更像是一个 security concern .因此,如果没有什么能阻止您启用 CORS,那么请坚持下去。

通过使用 promise 执行标准 $http.get$http.jsonp 请求的示例。

var app = angular.module("MyApp", []);

app.controller("MyCtrl", function($scope, $http){

$scope.data = "";

$scope.normalCall = function(){

var results = $http.get('http://202.133.56.91:8081/SD_BIO/app/retrievenotifications.action?subjStudyId=441')
.then(function(response){
$scope.data = response;
}, function(error){
$scope.data = error;
});

return results;
};


$scope.jsonPCall = function(){

var results =$http.jsonp("http://202.133.56.91:8081/SD_BIO/app/retrievenotifications.action?callback=JSON_CALLBACK")

.then(function(response){
$scope.data = response;
}, function(error){
$scope.data = error;
});

return results;
};

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<button ng-click="normalCall()">Original Call</button> |
<button ng-click="jsonPCall()">JSONP Call</button>
<br><br>
<div ng-model="data">{{data}}</div>
</div>
</div>

关于json - Angular JS - HTTP GET 请求抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32189061/

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