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.
In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple: Create a Chrome browser shortcut. Right click short cut icon -> Properties -> Shortcut -> Target.
Use addHeader Instead of using setHeader method, response. addHeader("Access-Control-Allow-Origin", "*"); * in above line will allow access to all domains .
To allow any site to make CORS requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's Origin header and use that value to set Access-Control-Allow-Origin , and must also set a Vary: Origin header to indicate that some headers are being set ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With