There are some caveats when it comes to CORS. First, it does not allow wildcards *
but don't hold me on this one I've read it somewhere and I can't find the article now.
If you are making requests from a different domain you need to add the allow origin headers.
Access-Control-Allow-Origin: www.other.com
If you are making requests that affect server resources like POST/PUT/PATCH, and if the mime type is different than the following application/x-www-form-urlencoded
, multipart/form-data
, or text/plain
the browser will automatically make a pre-flight OPTIONS request to check with the server if it would allow it.
So your API/server needs to handle these OPTIONS requests accordingly, you need to respond with the appropriate access control headers
and the http response status code needs to be 200
.
The headers should be something like this, adjust them for your needs:
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400
The max-age header is important, in my case, it wouldn't work without it, I guess the browser needs the info for how long the "access rights" are valid.
In addition, if you are making e.g. a POST
request with application/json
mime from a different domain you also need to add the previously mentioned allow origin header, so it would look like this:
Access-Control-Allow-Origin: www.other.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400
When the pre-flight succeeds and gets all the needed info your actual request will be made.
Generally speaking, whatever Access-Control
headers are requested in the initial or pre-flight request, should be given in the response in order for it to work.
There is a good example in the MDN docs here on this link, and you should also check out this SO post