DEV Community

Tim Perry
Tim Perry

Posted on • Edited on • Originally published at httptoolkit.tech

Will it CORS? - an automatic CORS explainer

Hey Dev.to - today I'm launching WillItCORS.com. It's a quick tool to help everybody learn & understand Cross-Origin Resource Sharing (CORS) requests.

CORS is the mechanism browsers use to decide how web applications can communicate with other services over HTTP. Restricting that is very important for security, but it's hard to understand how CORS works, which means sending HTTP requests to APIs can often be difficult & confusing.

Let's talk about why CORS is hard:

  • A simple GET request to another origin will always send, but whether you can read the response depends on specific headers that come back.
  • POST requests will sometimes send OK, but if you set a content-type, and it's not on the list of safe content types, then there'll be an extra preflight request first, to ask the server if the browser is allowed to send the request before it sends it. Even if that preflight says yes, you still might not be able to read the response.
  • To allow actually reading these responses, the server needs to respond with a Access-Control-Allow-Origin header that matches your origin. 'Match' here is quick specific: http://example.com/ doesn't match http://example.com, and * will match all origins, but only if your request doesn't have a credentials property set to 'include'...
  • Different ports on the same domain and different subdomains are all different origins, so it's quite easy to do unexpected CORS requests even just within your own services!
  • Lots of other things can trigger preflight requests too: listening for progress events on your request, for example, or setting any header except for the specific safe header list (and even then, with specific rules on the values).
  • ...

The full set of CORS rules are an impossible riddle, understood by effectively nobody.

This is annoying, so to fix it I've built this magic CORS machine: WillItCORS.com. Tell it what you want, and it'll walk you through exactly what to do, complete with ready-to-use code or specific & detailed explanations of why it won't work. Enjoy!

Top comments (1)

Collapse
 
zerquix18 profile image
I'm Luis! \^-^/

This is amazing! I still hate CORS. But this is amazing!