Revisiting CORS
Categories: programming
Tags: web javascript http
On a recent project I have repeatedly been annoyed by CORS related errors. Time to revisit CORS.
MDN’s CORS article
- Preflight requests are initiated prior to the request to check if the request is permitted
- Requesting to the same host is allowed by default, following same origin policy
- Origin is defined as:
- Protocol:
http
,https
- Port such as 443 or 80
- Host name
- Protocol:
- Exceptions to origin
- Protocols
data
,javascript
and special URLabout:blank
inherit from the document.about:blank
seems like an interesting edge case I should learn about at a future time. - Files have special rules but are not well defined within the document
- Protocols
- Origin is defined as:
- Pre-flight not triggered under all the following being true:
- Methods: {
GET
,POST
,HEAD
} - Only headers specified in the request: {
Accept
,Accept-Language
,Content-Language
,Range
}Content-Type
may also be included, however it must be one of the following: {application/x-www-form-urlencoded
,multipart/form-data
,text/plain
}
- Methods: {
- Valid Pre-flight response:
- 204 - No content
- Must include
Access-Control-Allow-Origin
, although may be*
to indicate all domains. Access-Control-Request-Headers
must contain all headers allowed.- If including credentials in a
fetch
requestAccess-Control-Allow-Credentials: true
must be returned.- Server must specify specific domains for
Allow-Origin
which must not be*
.
- Server must specify specific domains for
- Resulting resource must also include on each response:
Access-Control-Allow-Origin