Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to enable CORS when my API is on a subdomain of my main website?

Tags:

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

like image 574
JMK Avatar asked Nov 03 '14 22:11

JMK


People also ask

Is subdomain considered cross-origin?

Sub-domains are considered different and will fail the Same Origin Policy unless both sub-domains declare the same document.

Should API enable CORS?

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.

Should I use subdomain for API?

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.

Is CORS required for REST API?

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.


2 Answers

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.

like image 67
inf3rno Avatar answered Sep 20 '22 05:09

inf3rno


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

like image 32
Sashi Avatar answered Sep 23 '22 05:09

Sashi