Solved CORS policy: No 'Access-Control-Allow-Origin'

Let's start by understanding why you receive the following error message:

XMLHttpRequest cannot load ... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access.

As defined by Wikipedia, CORS (Cross-origin resource sharing) is a machanism which allows restricted resources (e.g fonts) to be requested from a domain outside the domain from which the first resource was served.

A common scenario where this error is encountered is as follows:

You have Javascript on Domain A (domaina.com) requesting information from Domain B (domainb.com). By default Domain B will not allow requests from a domain other than domainb.com. You can however allow all requests from all domains by adding the following to the .htaccess file on Domain B:

<IfModule mod_headers.c>
   Header set Access-Control-Allow-Origin "*"
   Header set Access-Control-Allow-Headers "Content-Type"
   Header set Access-Control-Allow-Methods "GET"
</IfModule>

Note that this permits requests from all domains. If you only want to permit requests from a particular domain:

<IfModule mod_headers.c>
   Header set Access-Control-Allow-Origin "http://PERMITTED-DOMAIN.com"
   Header set Access-Control-Allow-Headers "Content-Type"
   Header set Access-Control-Allow-Methods "GET"
</IfModule>

Another solution is to install a Chrome extension called "CORS Toggle" which can be found here. You should then have a little toggle button on the top right of Chrome which if turned on will prevent you from receiving CORS policy warnings.

Please remember to turn this off when you're done, unless you want the risk of malicious scripts running on compromised sites. The plugin essentially disables the default security mechanism in Chrome for preventing unwanted scripts from running on other domains.

Please let me know which solution you prefer and why in the comments below :)