JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Prev
javascript
senior
web-apis

What is CORS, when do CORS errors occur, and how can they be resolved?

cors
fetch
http
security
browser
same-origin-policy
preflight
Quick Answer

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.

Detailed Explanation

What is CORS?

  • HTTP-header based mechanism for cross-origin requests
  • Browsers enforce same-origin policy by default
  • Server must explicitly allow cross-origin access

What Triggers CORS?

  • Requests to different origin (protocol + domain + port)
  • Applies to: fetch(), XMLHttpRequest, Web Fonts, WebGL textures

Simple vs Preflighted Requests:

Simple Requests (no preflight):

  • Methods: GET, HEAD, POST
  • Standard headers only (Accept, Content-Language, Content-Type)
  • Content-Type: text/plain, multipart/form-data, application/x-www-form-urlencoded

Preflighted Requests (OPTIONS sent first):

  • Non-simple methods (PUT, DELETE, PATCH)
  • Custom headers (Authorization, X-Custom-Header)
  • Content-Type: application/json

Key CORS Headers:

  • Access-Control-Allow-Origin: Allowed origin(s) or *
  • Access-Control-Allow-Methods: Allowed HTTP methods
  • Access-Control-Allow-Headers: Allowed request headers
  • Access-Control-Allow-Credentials: Allow cookies/auth
  • Access-Control-Max-Age: Preflight cache duration

Code Examples

CORS error scenarios
// 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!
  }
});

Resources

MDN - Cross-Origin Resource Sharing (CORS)

docs

How to Debug Any CORS Error

article

CORS in 100 Seconds

video

Related Questions

What are Promises in JavaScript and how do they work?

mid
async

How do async/await work and how do they relate to Promises?

mid
async
Previous
Explain the Module pattern and how ES6 modules differ from CommonJS.