Overview
By default, browsers enforce the Same-Origin Policy (SOP), which prevents a script on one site from accessing data on another. CORS is the controlled way to relax this policy, allowing for legitimate cross-site requests (e.g., a frontend app calling an API on a different domain).
How it Works
- Simple Requests: The browser sends the request and checks the
Access-Control-Allow-Originheader in the response. - Preflight Requests: For complex requests (e.g., using
PUTor custom headers), the browser first sends anOPTIONSrequest to ask the server for permission.
Security Risk
Misconfigured CORS (e.g., using Access-Control-Allow-Origin: *) can allow any malicious site to steal sensitive data from your users if they are logged into your application.