what’s CORS
tags: learning networking
content
CORS
- Cross Origin Resource Sharing
- it’s a browser security mechanism
- an origin is protocol + domain + port
Note
Important: it’s the browser, not the server, enforcing CORS
scenario:
- simple web app
- frontend:
localhost:5173 - backend:
localhost:8080
- frontend:
- when browser needs frontend static files, requests are sent to
localhost:5173 - web server returns static files (e.g.,
coffee.js) coffee.jswants to requestslocalhost:8080/coffees- when browser is about to execute this api to
localhost:8080, it stops- because these are different origins
coffee.jsis fromlocalhost:5173coffee.jswants to requestlocalhost:8080
- because these are different origins
with nginx
- browser executes javascript
coffee.js(fromlocalhost:5173) coffee.jswants to getcoffeesresource- instead of
localhost:8080 - request is sent to
http://localhost:5173/api/...
- instead of
- nginx redirects
/api/traffic tohttp://localhost:8080 - backend is listening on
8080, backend receives request
Note
before nginx, browser requests to frontend and backend are different.
localhost:5173andlocalhost:8080- browser stops this, because they are different origins
with nginx, browser requests are only sent to
localhost