What exactly is CORS, and how does it work?
Thread 🧵
Thread 🧵
CORS (Cross-Origin Resource Sharing) is an HTTP-based mechanism that enables the browser to access resources outside a given domain.
In other words, resources can be requested from one URL to another.
In other words, resources can be requested from one URL to another.
As a standard, browsers implement Same-Origin Policy, which means requesting data from the same origin is allowed but requesting data from another URL will throw an error.
This is implemented for security reasons.
This is implemented for security reasons.
However, using CORS adds flexibility to Same-Origin Policy. A typical example is making a request to an API on a different domain.
Below is a breakdown of how CORS functions👇🏼
Below is a breakdown of how CORS functions👇🏼
When the browser makes a cross-origin request, it will add an ‘Origin’ header that states the scheme(protocol), domain, and port number.
Next, the server responds and adds an ‘Access-Control-Allow-Origin’ header in the response.
If this header’s origin is the same as the origin sent in the request, access to the resource will be allowed.
If this header’s origin is the same as the origin sent in the request, access to the resource will be allowed.
That's the basics of a CORS request. However, some HTTP methods (Methods that are not GET, POST, or HEAD) require a preflight request before the actual request is made.
Details of Preflight requests 👇
Details of Preflight requests 👇
Preflight requests start by sending an HTTP OPTIONS request to the server.
The server responds with an ‘Access-Control-Allow-Methods’ header which states the HTTP Methods permitted to be used by the origin.
The server responds with an ‘Access-Control-Allow-Methods’ header which states the HTTP Methods permitted to be used by the origin.
The response may also include an ‘Access-Control-Max-Age’ header specifying the time the response must be cached within.
With this, the client won’t need the preflight request whenever it wants to access the CORS resource.
The actual CORS request can now be made as usual.
With this, the client won’t need the preflight request whenever it wants to access the CORS resource.
The actual CORS request can now be made as usual.
That’s all for now!
Follow @Rapid_API for more exclusive content. 🐙
Follow @Rapid_API for more exclusive content. 🐙
Loading suggestions...