I have a RESTful api sitting at a subdomain of my website, so it is setup like below:
api.blah.com - RESTful api blah.com - Website
When I try to do HTTP requests though, I get the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '(index)' is therefore not allowed access.
I thought that because it was on the same domain, this should work, do I need to enable CORS or is there something else I need to do?
The API is built on ASP.Net Web API, and website is AngularJS based.
Thanks
Sub-domains are considered different and will fail the Same Origin Policy unless both sub-domains declare the same document.
CORS is typically required to build web applications that access APIs hosted on a different domain or origin. You can enable CORS to allow requests to your API from a web application hosted on a different domain.
You don't need a subdomain for your API, like api.example.com or a sub-path, like example.com/api . Your endpoint should be the root of your webpage: example.com . This is useful, because as discussed above the URL should be both the identifier as the locator of a single resource.
Cross-origin resource sharing (CORS) is a browser security feature that restricts cross-origin HTTP requests that are initiated from scripts running in the browser. If your REST API's resources receive non-simple cross-origin HTTP requests, you need to enable CORS support.
Yes you have to enable it. You have to send CORS allow headers from server side to your browser. This is because a subdomain counts as a different origin. You probably have to allow HTTP methods like PUT, DELETE, OPTIONS as well. At least I guess angular sends that kind of requests too. You have to handle preflight requests (OPTIONS) by these new methods.
The origin is a combination of scheme/host/port. So, if your origin is http://store.company.com/ and you are trying to access http://news.company.com/dir/page.html, it would be considered cross origin. More examples here -
Same-origin policy
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