Interview frequency: …
Short answer
CORS is a browser security mechanism that prevents malicious websites from reading your site's data. The browser sends an OPTIONS preflight to check server permission before sending modified or complex requests.
Explanation
The Same-Origin Policy (SOP) prevents a script on foo.com from reading a response from api.bar.com. For a complex request (using PUT/DELETE, custom headers such as Authorization, or a nonstandard Content-Type such as application/json), the browser first sends an OPTIONS request with Access-Control-Request-Method. If the server responds with matching allow headers (Access-Control-Allow-Origin), the browser sends the actual request; otherwise, it blocks it and reports a console error.
Code example
// Allowed server response:
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-TypeCommon mistakes
- Setting Access-Control-Allow-Origin: * together with credentials: true, which browsers completely prohibit for security reasons.