Security

What is CORS and how do you fix CORS errors?

How CORS works: what an origin is, why browsers block cross-origin reads, how preflight requests and Access-Control-Allow-Origin work, and how to fix errors.

  • 6 min read
  • 5 questions
  • +35 XP
Transcript

CORS explained by cats. Kitty wants fish. Kitty goes to the tuna restaurant. She orders tuna, no problem. Same origin. Waiter serves it right away. Then Kitty says, Waiter, bring me milk from the milk shop. The waiter pauses. We are not a milk shop.

Different origin. Waiter can't fetch from another place, unless the place allows it. So the waiter calls the milk shop. If the chef responds with a special note, the waiter serves milk across. If the header isn't there or it doesn't match, the waiter blocks it.

Kitty gets nothing. That's CORS. Cross -origin resource sharing. One website asking another for resources. The browser enforces the rules. The server decides who gets served. Without CORS, any cat could grab food from anywhere. With CORS, only trusted origins are allowed.