简体   繁体   中英

Loading JSON cross-domain using an HTTPS url with AngularJS

I'm trying to get some JSON data from an URL using the following AngularJS code:

'use strict';

/* Controllers */

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function($scope, $http) {
  $scope.test = "Not loaded";
  delete $http.defaults.headers.common['X-Requested-With'];
  $http.get('https://live.mpare.net/users.json').success(function(data) {
    $scope.test = data;
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
  ;
});

However, the JSON file isn't loaded. If I try a different URL, namely http://ip.jsontest.com , it does work.

I've retrieved the header for the https website using curl:

HTTP/1.1 200 OK
Date: Sat, 08 Nov 2014 10:53:04 GMT
Server: Apache/2.2.29 (Amazon)
X-Powered-By: PHP/5.3.29
Set-Cookie: PHPSESSID=epp00ffbe0nmtogpj8dcvnfvg2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 119
Connection: close
Content-Type: application/json

The header for the http website looks like this:

HTTP/1.1 200 OK
Date: Sat, 08 Nov 2014 10:53:04 GMT
Server: Apache/2.2.29 (Amazon)
X-Powered-By: PHP/5.3.29
Set-Cookie: PHPSESSID=epp00ffbe0nmtogpj8dcvnfvg2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 119
Connection: close
Content-Type: application/json

How can I load the https JSON file?

对于跨域,您必须使用CORS,请在此处查看CORS上的这篇文章,如果需要可以使用jsonp,但是您不能使用jsonp进行发布。希望它会有所帮助

What worked was the following:

replace $http.get with $http.jsonp and put ?callback=JSON_CALLBACK at the end of the url. The following code worked for me:

'use strict';

/* Controllers */

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function($scope, $http) {
  $scope.test = "Not loaded";
  delete $http.defaults.headers.common['X-Requested-With'];
  $http.jsonp('https://live.mpare.net/users.json?callback=JSON_CALLBACK').success(function(data) {
    $scope.test = data;
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
  ;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM