Apache/Nginx/Xampp apache enable CORS Access-Control-Allow-Origin for Angular Js

More information, you should check here: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
How CORS works:
1
The browser sends the OPTIONS request with an Origin HTTP header. The value of this header is the domain that served the parent page. When a page from http://www.foo.com attempts to access a user’s data in bar.com, the following request header would be sent to bar.com:

Origin: http://www.foo.com

The server may respond with:
An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed. For example:

Access-Control-Allow-Origin: http://www.foo.com

Preflight example
When performing certain types of cross-domain AJAX requests, modern browsers that support CORS will insert an extra “preflight” request to determine whether they have permission to perform the action.

OPTIONS /
Host: bar.com
Origin: http://foo.com

If bar.com is willing to accept the action, it may respond with the following headers:

Access-Control-Allow-Origin: http://foo.com
Access-Control-Allow-Methods: PUT, DELETE


Virtual Host: (allow the methods that come as Cross Domain Request)

Header set Access-Control-Allow-Origin "*"                   
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header set Access-Control-Allow-Headers "X-Access-Token, X-Key, Origin, X-Requested-With, Content-Type, Accept"

.Htaccess: (allow options method and rewrite rule)

RewriteEngine On
# cors rule
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ blank.html [QSA,L]
# rewrite rule
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Angular code: (allow cross domain request)

angular.module('configurations', [])
.config(function ($httpProvider) {
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];
})

Nginx code: (allow cross domain request)

add_header Access-Control-Allow-Origin  "*";
add_header Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT";
add_header Access-Control-Allow-Headers "X-Access-Token, X-Key, Origin, X-Requested-With, Content-Type, Accept";
location /api-mobile {
    index index.php;
    try_files $uri $uri/ /api/index.php?$args;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s