CORS Explained
to Advanced)
(Beginners
Origin
GET XCSS
Domain-X.com
Client
Origin: GET
Domaln-Y.com
Domain-X.com
Access-Control-Allow-Orgin: + Other Domain
E Problem: Why to use CORS ?
Imagine you have a private database (your
backend server) and only want your website
to access it. But other websites also try to
fetch your data.
To stop browsers use Same-Origin
this,
Policy (SOP), which blocks requests from
different websites unless permitted.
Browser
example.com
JavaScript Server
request
fetch(api.example.com/func) Ifunc endpoint
response
Blocked
Solution: CORS
(Cross-Origin Resource Sharing)
CORS is like a
permission system that lets
your server decide:
1.Which websites can access your data.
2.What types of requests (GET, POST, PUT,
DELETE) are allowed.
3.What data (headers) can be shared.
Enable CORS in the Backend
K Fix: Add in Node.js +Express:
const cors = require('cors');
ppp.use(cors ({
origin: "https:/lexample com", .
methods: "GET, POST, PUT, DELETE",
allowedHeaders: "Content-Type, Authorization"
));
Key Takeaways: CORS
• CORS allows safe data sharing between
different websites.
The server must allow specific domains to
acces its data.
• Preflight requests (using OPTIONS) check
if the server allows special requests.
Client GET style.css
Origin
xdomain.com
GET font.wotf
Origin: xdomain.com
Access-Contro-Allow-Origin:
Other Domain
ydomain.com