CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks cross-origin requests unless the server explicitly allows them via HTTP headers like Access-Control-Allow-Origin.
What is CORS?
What Triggers CORS?
fetch(), XMLHttpRequest, Web Fonts, WebGL texturesSimple vs Preflighted Requests:
Simple Requests (no preflight):
text/plain, multipart/form-data, application/x-www-form-urlencodedPreflighted Requests (OPTIONS sent first):
application/jsonKey CORS Headers:
Access-Control-Allow-Origin: Allowed origin(s) or *Access-Control-Allow-Methods: Allowed HTTP methodsAccess-Control-Allow-Headers: Allowed request headersAccess-Control-Allow-Credentials: Allow cookies/authAccess-Control-Max-Age: Preflight cache duration// Frontend code (https://myapp.com)
// This triggers CORS error if server doesn't allow it
fetch('https://api.other-domain.com/data')
.then(res => res.json())
.catch(err => {
// "Access to fetch at 'https://api.other-domain.com/data'
// from origin 'https://myapp.com' has been blocked by CORS policy"
console.error('CORS error:', err);
});
// Preflight triggered by JSON content-type
fetch('https://api.other-domain.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Triggers preflight!
},
body: JSON.stringify({ name: 'test' })
});
// Preflight triggered by custom header
fetch('https://api.other-domain.com/data', {
headers: {
'Authorization': 'Bearer token', // Triggers preflight!
'X-Custom-Header': 'value' // Also triggers preflight!
}
});