1

I am trying to access an API via my localhost using the following code:

  $.ajax({
            url: "http://domain.xxx.net/api/tokens.json?email=xxx@xxx.net&password=xxx",
            //method: "GET",
            headers: { "Accept": "application/xml", "Content-Type": "application/xml", "Access-Control-Allow-Origin": "*"},
            dataType: "JSON",
            success:function(data){
                alert(data);},
            success:function(e){
                alert(e.message);}

    });

I have read over the internet that this is not possible due to the error below.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

After some research it was said that i can use JSONP or CORS. I was able to use JSONP however, I am getting a js error because the API supports only both JSON & XML and not JSONP. Now I am trying to convert my ajax call to CORS but I simply can't understand the syntax. I always get the same error about the 'Access-Control-Allow-Origin'.

I hope someone can help me translate this one. Thanks.

  • 1
    CORS support has to be implemented by the server...so unless you have control over the server you can't do much – Arun P Johny May 14 '15 at 05:28
  • CORS is not something you really change in JS, it's done by the server... – dandavis May 14 '15 at 05:28
  • I had the same problem, you have to enable Access-Control-Allow-Origin from the server api side. It had nothing to do with the header – Mindless May 14 '15 at 05:29
  • If the server doesn't support either CORS or JSONP then another possible solution is to use your web server to make the remote API calls.. ie from your site sent a ajax request to your web server and from the server you can make the remote api calls – Arun P Johny May 14 '15 at 05:31

3 Answers3

0

Access-Control-Allow-Origin should be in the response header. It sounds the server from which you're trying to get the data did not enable CORS (set a response header of Access-Control-Allow-Origin). If this is the case I don't think you'll be able to get your resource through Javascript. You'll need to do it from the backend.

paradozx
  • 108
  • 1
  • 10
0

You can't do that from browsers. You need do that from the backend. If you want to use javascript, you can use NodeJS

0

To those who wants to access cross domain for testing purpose. A possible work around is to disable your browser's web security.

For chrome users: Close all your browser's session then in your terminal run the command below:

open -a Google\ Chrome --args --disable-web-security

Hope this one helps.