Skip to main content

I recently developed several APIs and a friend of mine ([+Jacob Pawlik]( developed the frontends. While developing we always ran into the „Origin is not allowed by Access-Control-Allow-Origin“ (Google Chrome wording) error which was really annoying. You can temporarily fix this by telling your browser to disable web security, but you can´t this to your customers….They will hardly believe that you are running a serious business.

### What is the cause?
By default you are not allowed to fetch content with JavaScript from another domain/port source. Even other subdomains are disallowed. „Why is that?“ : This is purely for security reasons because this way a hacker script is not able to receive or send sensible data from/to it. This behaviour is called „same origin policy“.

### _“But I am creating an API that I want other services to access it!“__ _
Well, if you want your API to be consumable by other domains/ports, then you have to configure your web server a little bit. I am using Apache 2 under Linux for my servers, so I will show you how I solved it:

First I had to enable the headers module by invoking: _a2enmod headers _on the console.
After this, I added _Header set Access-Control-Allow-Origin „*“_ to my _<VirtualHost>_ section in my web site configuration. Finally I had to restart the apache to enable the module and the new configuration. Done!
You can use the header directive not only in _<VirtualHost>_, but also in _<Directory>_,_ __<Locations>_,_<Files>_ and _.htaccess _files_._
_I hope this helps you bypassing this very useful, but during development annoying restriction.

Daniel Sachse

Author Daniel Sachse

More posts by Daniel Sachse