I just suffered quite a lot while trying to use an API someone provided me to hack up a dashboard. This was because it was missing the necessary headers to enable CORS to work from a web-app.
What is CORS?
Suffice to say that CORS is away to allow your web-app to request resources from a server other than the one it came from.
Make My Web-App Work!
Chances are, if you’re here, you’re currently writing a web-app (maybe Angular or React?), and you are trying to get data from a URL, and it is failing with the word CORS in your dev-tools console.
This is because the “Access-Control-Allow-Origin” header is not being added by the server. So, your client app is not allowed to use it. In terms of the blog referred to earlier, you’re not on the guest list.
If you’re in a company, the correct fix for this is to have the API add the header with the proper origins, or a * if you’re not overly worried about security. But, often you don’t have time for that, or you’re not in control of the API. In that case, you can use a proxy!
Assuming you are working on Linux and you’ve already installed Apache (HTTPD), it is pretty easy to fix this with a proxy. Here is a perfect example. Just add this at the bottom of /etc/httpd/conf/httpd.conf, ensure there is a “Listen 80” in your file, and then restart Apache with “sudo systemctl restart httpd”.
<br /><LocationMatch "/SomePath"> ProxyPass http://:8080/SomePath Header add "Access-Control-Allow-Origin" "*"
This will make sure all requests to this server, whether they’re from it or another host, which target :8080/SomePath will be proxied to http://:8080/SomePath and will return to the client with the extra header “Access-Control-Allow-Origin” “*”. This will let your web-app correctly talk to URLS under http://:8080/SomePath even though it doesn’t have CORS headers itself.
Note that you can do / instead of SomePath to target the whole server, and of course, you can change the ports/etc.
I hope this helps you!
Oh, and one more thing… If you installed Apache and are having trouble running it in the first place, maybe you’re running SELINUX, in which case you might want to try “/usr/sbin/setsebool -P httpd_can_network_connect 1”. That nailed me before I went on to work on the rest of this.
Also, if you want to use a different port and it’s not working on Centos/etc, you may need to open the port in SELINUX “semanage port -a -t http_port_t -p tcp 8222”.