You must have already been through the situation of trying to log in to some application, type your data, click send and nothing happens on the page. The first thing a developer does is inspect the page and then open the browser console (by clicking the F12 button or pressing the right mouse button, then Inspect).
You get the error "blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted." or similar.
But do you know what causes it?
Same-origin policy
The same-origin policy is a security mechanism that restricts the way a document or script from one origin interacts with a resource from another origin. And what is it for? Helps to prevent malicious attacks.
Two URLs share the same origin if the protocol, port (if specified), and host are the same.
how do we handle situations where our frontend needs to consume an API with different url without having issues with CORS? As in case we want to connect an API running on port 8000 with a React application running on port 3000?
When sending a request to a different origin API, the server needs to return a header called Access-Control-Allow-Origin. Inside it, it is necessary to inform the different origins that will be allowed, such as: Access-Control-Allow-Origin: http://localhost:3000/.
It is possible to allow access from any origin using the asterisk symbol: Access-Control-Allow-Origin:
.* This is not a recommended measure as it allows unknown origins to access the server, unless it is intentional as in case of a public API.
After all, what is CORS?
CORS (Cross-origin Resource Sharing) is a mechanism used to add HTTP headers that tell browsers to allow a web application to run on one origin and access resources from a different origin. This type of action is called a cross-origin HTTP request.
It is used to enable cross-site requests for XMLHttpRequest or FetchAPI calls (cross different origins), web fonts (@font from CSS), WebGL textures, and drawing frames using drawImage().
Top comments (0)