Today, I am going to show you guys how to enable cross-origin resource sharing on an apache server. Before we start, I would like to ask you a question. Have you ever come cross this error message while development? To be more specific, here is what the error message might look like.
If yes, then you are in luck. By following this tutorial, you may solve this problem. So, what exactly is cross-origin resource sharing? Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. file) on a web page to be requested from another domain outside the domain from which the resource originated. For example, a HTML page served from http://www.domain-a.com makes a <img> src request for http://www.domain-b.com. For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, in the error message shown above, the script in HTML was trying to make a XMLHttpRequest and Fetch some JSON from domain namely the https://www.jenrenalcare.com. However, the HTML page was served from https://s.codepen.io. As we know, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain. So, how do we solve this in the server side? Here are the steps that what you should do. First, change directory to where you put your apache conf file.
command to change directory to apache conf file
Then, you need to have administrator access or sudo to modify the apache conf file. Then do the following commands,
command to vi the apache conf file
Then, add the following lines to your code.
apache code for enable the CORS
source code hosted on GitHub
Simple hul!? Now, you may simply save the file and quit. Then, in fact, for Header to work in apache, we need to run the following command.
command to enable Header for apache
Now, we are left with only one command to make it work. We simple need to restart the apache!
restart your Apache2 server
Hopefully this guide has given you the confidence to fix the CORS problem on the server side when you see them. I hope that this tutorial has helped you and thank you for reading!
I’ll try to keep this list current and up to date. If you know of a great resource you’d like to share or notice a broken link, please let us know.