CORS Explained
CORS Explained
@ sanuj bansal
Meet the Problem
You’re building a website: http://frontend.com
Your data is on: http://backend.com
You try to fetch data from the backend...
And boom — you get this:
@ sanuj bansal
What Just Happened?
@ sanuj bansal
What is an “Origin”?
Same origin:
http://site.com:80 → http://site.com:80
Cross origin:
http://site.com → http://api.site.com
http://localhost:3000 → http://localhost:5000
Different origins trigger CORS checks!
@ sanuj bansal
How Does CORS Work?
1.You send a request from frontend.com
2.Browser asks the server:
“Hey, can this origin access your resources?”
1.Server must respond with this header:
@ sanuj bansal
What If It’s a POST or
Custom Header?
1.Now things get a little fancy…
2.The browser sends a preflight request using OPTIONS:
@ sanuj bansal
Fixing CORS in Code
(Express.js Example)
@ sanuj bansal
Fixing CORS in Spring
Boot
@ sanuj bansal
Quick CORS Tips
@ sanuj bansal
Follow For More
Such Content !
Sanuj Bansal
Senior Developer