7

I am using AngularJS, but I've encountered the same issue with JQuery and in plain JavaScript as well. If the remote server I am accessing sets Access-Control-Allow-Origin then either the success or error methods is invoked.

When there is no Access-Control-Allow-Origin neither of those is called and I can only see the error in the console. Is there a way to capture the No Access-Control-Allow-Origin error in my JavaScript code?

And just in case you are interested in a use-case, I am building a front-end for PyPi https://pypi.python.org/ There, you can get the information about packages in JSON format. (e.g. https://pypi.python.org/pypi/dspy/json ). Those requests set the Access-Control-Allow-Origin, but if I send a request for a package that is not on the server (e.g. https://pypi.python.org/pypi/dspyz/json ) then I get No Access-Control-Allow-Origin and thus I don't get anything invoked in my JavaScript code.

Update

After some more experiments I found out that the error method was called it just threw an exception due to some issue with the code I used and that mislead me.

szabgab
  • 6,202
  • 11
  • 50
  • 64

1 Answers1

3

This is not possible because of security reasons. Sniffing the users local network would be possible.

Further information here.

Link credits to eithedog for his comment.

Community
  • 1
  • 1
Dustin Hoffner
  • 2,025
  • 1
  • 14
  • 15
  • Does that mean that the JavaScript code does not know about the request being rejected? Is it just silently not answered as if it was a timeout? – szabgab Apr 17 '15 at 17:56
  • 1
    Yes, I just tried it again. You get exactly the same kind of error object, when you listening on `xhr.onerror` wether it's a `timeout` or a `No Access-Control-Allow-Origin`. The only way you can distinguish these errors in a unsecure way is to track the time gone since you started the request. – Dustin Hoffner Apr 17 '15 at 18:06