Categories
Uncategorized

Handling CORS and API

CORS

Handling CORS (Cross-Origin Resource Sharing) can be quite tricky at times.  Browsers restrict Cross-Origin HTTP requests due to security reasons. For example, the XMLHttpRequest doesn’t work for external domains. With CORS, XMLHttpRequest 2 allows that.

To handle the Cross-Origin requests on modern browsers, there is an easy workaround. A backend technology like PHP, nodejs, .NET, Java or Ruby on Rails can be used to route externals API calls through them, instead of directly calling the API from the frontend technologies like jQuery and AngularJS.

For example I have written a simple program using PHP 5.6 in the backend and AngularJS on the front end to initiate the CORS.

DEMO

Code

If you are having trouble handling the COR’s on the API side and have access to the Apache config file(ex: apache2.conf) on your API server, then you can enable the settings by adding this line in your Directory or Virtual Hosts tag.

Header set Access-Control-Allow-Origin "*"

To allow only a particular domain,

Header set Access-Control-Allow-Origin "your-domain.com"

If you do not have access to the apache config file, then you need to include the following header in your API service file, to allow Cross-Origin requests made to it. Not initiating this may lead to 403 errors as response. To allow any domain to request the API, you can use the following piece of code in your php file.

 <?php
     header("Access-Control-Allow-Origin: *");
     ...
  ?>

To allow only a certain domain to make requests to your API, you can use the following line of code.

 <?php
     header("Access-Control-Allow-Origin: your-domain.com");
     ...
  ?>

If you have any other ideas regarding CORS, you can add a comment below.