What is CORS
CORS stands for Cross-Origin Resource Sharing. It’s a security feature implemented by web browsers to prevent malicious websites from making unauthorized requests to another site. When it happens, you typically see the below error:
Access to XMLHttpRequest at 'https://api.example.com/data' from
origin 'https://www.example.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
When a web application running on one domain tries to make a request to a different domain, the browser blocks the request by default unless the server explicitly allows it. This restriction helps protect users’ data and prevent cross-site scripting attacks. However, it can sometimes cause issues for legitimate web applications that legitimately need to access resources from other domains.
Four Response Headers for CORS
- Access-Control-Allow-Origin: Used to set the allowed origin address for cross-origin requests (both preflight and actual requests are validated during cross-origin requests).
- Access-Control-Allow-Headers: Specifies the special header fields allowed to be carried during cross-origin requests (only validated during preflight requests).