Just one of the things I'm learning. https://github.com/hchiam/learning
Set CORS on a server: https://web.dev/cross-origin-resource-sharing
browser sends Origin
-> server responds with Access-Control-Allow-Origin
-> browser (dis)allows response data to client site
https://cors-demo-hchiam.glitch.me/
- Go to some other URL (for example, a blank page or https://www.wikipedia.org/).
- Open the console log of developer tools in your browser.
- Enter this:
var a = fetch('https://cors-demo.glitch.me/', {mode:'cors'}); a;
- This should be blocked by CORS.
- It's blocked because the
server.js
response is only simplyresponse.sendFile(__dirname + '/message.json');
- Enter this:
var b = fetch('https://cors-demo.glitch.me/allow-cors', {mode:'cors'}); await b;
- This should not be blocked by CORS.
- Any origin is allowed because the
server.js
also sets a headerresponse.set('Access-Control-Allow-Origin', '*');
in the response before sending the responseresponse.sendFile(__dirname + '/message.json');
.
- Sending credentials cookies with CORS (unusual) requires additional headers:
- Request:
credentials: 'include'
(For example:fetch('https://example.com', { mode: 'cors', credentials: 'include' })
) - Response:
Access-Control-Allow-Origin
must be specific origin and you must incldueAccess-Control-Allow-Credentials: true
.
- Request:
-
"Complex" HTTP requests require preflight requests
-
"Complex" request:
- uses methods other than "GET", "POST", or "HEAD"
- has headers other than
Accept
,Accept-Language
orContent-Language
- has
Content-Type
header other thanapplication/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
-
Preflight:
-
Example request sent before the actual message:
OPTIONS /data HTTP/1.1 Origin: https://example.com Access-Control-Request-Method: DELETE
-
Example response:
HTTP/1.1 200 OK Access-Control-Allow-Origin: https://example.com Access-Control-Allow-Methods: GET, DELETE, HEAD, OPTIONS Access-Control-Max-Age: <optional-seconds-cache-results-to-not-preflight-request>
-
-