< Cross-Origin Resource Sharing />
Before Jan 2014 AJAX requests across domains were not possible When W3C added CORS as a recommendation. As name defines it helps in sharing resources, data across interdomain.
To let Cross-origin request work, we need to pass headers with Access-Control-Allow-Origin
in a request and it will help in resolving its response for the request else response will not be resolved due to the source being from an alien domain.
2 major issues that you may encounter while CORS request:
- Preflight-Request.
- Actual Execution Request.
So if you got confused then here is how it works. when you fire a request let’s say a `DELETE` request is to be made. First, it will fire a Preflight Request to check whether the `DELETE` request is allowed or not and then it will make an actual request.
Before an actual request be made to the server every request has a pre-request which confirms whether the actual request can be made called Preflight request.
Cors are handled both at Client-End & Server-End.
Error due to Server-End Config
If a preflight request fails, you will get the error like
Response to preflight request doesn't pass access control check:
Then, if an actual request fails due to CORS precisely, you will end up with
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Error due to Client-End headers missing
Origin is not allowed by Access-Control-Allow-Origin.
In order to resolve domain for access, syntax vice you can allow access either to one domain or to all. Otherwise, you will have to dynamically change a domain inside the code.
If you want to allow for CORS through HTML like this using meta tag, Won’t work
<meta http-equiv="Access-Control-Allow-Origin" content="*">
In JS
With your request, headers are required
To Allow single domain:
‘Access-Control-Allow-Origin’: ‘http://example.com’
}
To Allow all domains:
‘Access-Control-Allow-Origin’: ‘*’
}
Using PHP
header("Access-Control-Allow-Origin: http://example.com");
Also while making a request to other domain, if you are not able to get rid of cross-origin errors after using methods above, you may have to put CORS access at the server end because for obvious reasons you cannot access data from the server until it allows(authorizes) you to.
A great Developer always has great sets of tools
- Test your API response for CORS errors test-cors.org
- Chrome Console – CORS error is always displayed in chrome console if not in Network response.
- MOESIF ORIGINS & CORS CHANGER plugin –
This plugin allows you to send cross-domain requests directly from the browser without receiving Cross-Origin Errors.
You can override the Request Origin header with this plugin and also have Access-Control-Allow-Origin set to *. Also, you can override:
Request Headers: Origin
Response Headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials