1

I am trying to communicate with an API (http://labs.skanetrafiken.se/api.asp) from a react app.

However I keep getting blocked

var url = 'http://www.labs.skanetrafiken.se/v2.2/neareststation.asp?x=55.720504899999995&y=13.1927948'
$.ajax({
  type: "GET",
  url: url,
  async: true,
  dataType : 'xml',
  crossDomain:true,
  success: function(data, status, xhr) {
    console.log(data);
  }
});

Receives the response:

XMLHttpRequest cannot load http://www.labs.skanetrafiken.se/v2.2/neareststation.asp?latitude=55.720504899999995&longitude=13.1927948.
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://stackoverflow.com' is therefore not allowed access.

However when I try the same request from my terminal like this

curl "http://www.labs.skanetrafiken.se/v2.2/neareststation.asp?x=55.720504899999995&y=13.1927948&R=1000"

I get exactly the response I am looking for. How can I circumvent this? It would be nice to not have to set up a server with the only purpose of curling the API.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Albin
  • 2,912
  • 1
  • 21
  • 31
  • http://stackoverflow.com/questions/10068963/how-to-parse-xml-cross-domain-in-jquery – pawel Sep 29 '15 at 11:02
  • If you don’t control the server-side config for http://www.labs.skanetrafiken.se/v2.2/neareststation.asp such that you can make it send the `Access-Control-Allow-Origin` header in responses then your only option is to set up a (simple) proxy in the same origin your request comes from. Because the restriction here is set by browsers and there’s no way to trick browsers into bypassing it (short of setting up a proxy in the same origin). – sideshowbarker Sep 29 '15 at 11:30

3 Answers3

2

You can not do this request from Javascript because No 'Access-Control-Allow-Origin' header is present on the requested resource.

So resource http://www.labs.skanetrafiken.se does not have allowed cross-domain requests. While this Access-Control-Allow-Origin attribute will not be setted to * or other allowed domain on server of http://www.labs.skanetrafiken.se, you can't do the cross-origin requests to the API.

Description of CORS

MysterX
  • 2,318
  • 1
  • 12
  • 11
1

As others have wrote, this is a security mechanism of web browsers, you can't just make cross-domain requests as you wish (this prevents an awful lot of XSS attacks). CORS can be used to allow certain types of requests, but it seems that the site does not support this.

So you can either ask the service provider to fix their service, or do the API call in your backend, and send the JSON results to your clients.

CURL works because it does not have so strict security measures as a web browser.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
0

You'll need make a CORS (Cross-Origin Resource Sharing) request. I'd like to refer to this article.

Orry
  • 659
  • 6
  • 21