1

I am trying to load a json file cross domain, from http://xinruima.me/game/themes.json

I tried to write this in AngularJs for ES6:

  getThemesOptions() {
    const url = `http://xinruima.me/game/themes.json`;
    return this.$http.jsonp(url)
      .success(function(data){
          console.log(data);
      });
  }

It give me error: enter image description here

And then I found this online: http://jsfiddle.net/subhaze/a4Rc2/114/ It's an example to call a public api using the same syntax I wrote, it works. enter image description here

But when I change the url to my url, it gives the error as I shown above:

I tested my json file and it's valid.

Any advice?

Xinrui Ma
  • 2,017
  • 4
  • 26
  • 47

1 Answers1

1

The problem is that http://xinruima.me/game/themes.json URL is not a JSONP response, but a regular JSON.

The error is the browser trying to parse your JSON response as Javascript. Which does not happen to your fiddle requst, as the url http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK is a valid JSONP response.

You could use $http.get instead of $http.jsonp

getThemesOptions() {
    const url = `http://xinruima.me/game/themes.json`;
    return this.$http.get(url)
      .success(function(data){
          console.log(data);
      });
  }

But the request to http://xinruima.me/game/themes.json does not allow cross-domain requests so you will still have an error. On Chrome, for example, you can disable the cross-domain security policy but this would be good just while in development and if you don't have control over the server on xinruima.me you won't be able to overcome this security limitation.

EDIT:

As JSONP seems not be an option, you can check this SO question for possible ways of overcoming cross-domain errors.

Community
  • 1
  • 1
Felipe Sabino
  • 16,519
  • 5
  • 67
  • 110
  • I do have full control the server of xinruima.me, what should I do to overcome that limitation? Thanks – Xinrui Ma Oct 15 '16 at 20:54
  • You have to add cross-domain headers (`Access-Control-*`) allowing the request from your origin (place/domain where this angular app is hosted) so that the browser knows it is a safe call. Check this MDN _CORS_ article for more info https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – Felipe Sabino Oct 15 '16 at 20:57