What Is CORS in JavaScript?
CORS allows cross-origin requests. Here is how it works and why it matters.
What Is CORS in JavaScript?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls when a web page can make requests to a different origin.
What Is an Origin?
An origin is the combination of protocol + domain + port. http://example.com:80 and https://example.com:443 are different origins.
Same-Origin Policy
By default, browsers block cross-origin requests (same-origin policy). CORS is the mechanism that allows servers to opt-in to cross-origin requests.
How CORS Works
- The browser makes a request to a different origin.
- The server responds with CORS headers:
Access-Control-Allow-Origin: https://myapp.com(or*for any).Access-Control-Allow-Methods: GET, POST, PUT, DELETE.Access-Control-Allow-Headers: Content-Type, Authorization.
- The browser checks the headers. If allowed, the response is available to JavaScript. If not, the browser blocks it.
Simple Requests
"Simple" requests (GET, POST with simple content types) are sent directly. The browser checks the response headers.
Preflight Requests
"Non-simple" requests (PUT, DELETE, custom headers, JSON content type) trigger a preflight OPTIONS request first.
The Takeaway
CORS: a browser security mechanism for cross-origin requests. The server must include Access-Control-Allow-Origin and related headers. Simple requests are sent directly. Non-simple requests trigger a preflight OPTIONS request first. CORS is configured on the server, not the client.
Cross-Origin Resource Sharing. A browser security mechanism that controls when a web page can make requests to a different origin (protocol + domain + port). The server must include Access-Control-Allow-Origin headers to allow cross-origin requests.
A browser security policy that blocks requests to different origins by default. CORS is the mechanism that allows servers to opt-in to cross-origin requests by including specific headers.
Access-Control-Allow-Origin (which origins are allowed), Access-Control-Allow-Methods (which HTTP methods), Access-Control-Allow-Headers (which custom headers), and Access-Control-Allow-Credentials (for cookies).
Server-side. CORS is configured on the server by including the appropriate headers. The browser enforces it by checking the headers. You cannot 'fix' CORS from the client side (the server must allow your origin).
The combination of protocol, domain, and port. http://example.com:80 and https://example.com:443 are different origins. A request from one origin to another is a cross-origin request, which requires CORS.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

