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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I do have full control the server of xinruima.me, what should I do to overcome that limitation? Thanks
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 developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.