Skip to main content

Cross-Origin Resource Sharing

By default, an HTTP request can only be made within the current site. When trying to send a request to a different domain, port or protocol, that is, to make a cross-domain request, the browser throws an error. This is done for security reasons, and permissions are configured on the back-end. If the back-end does not support cross-domain requests, the front-end developer cannot do anything about it in their code.

Note

This browser policy is called CORS, Cross-Origin Resource Sharing, where Origin is the domain, port or protocol. This means resource sharing between various sources.

With each request, the browser adds the Origin HTTP header, with the URL of the web page that wants to make an HTTP request. For example, if you make a fetch request from the web page https://my-site.com/about to https://my-api.com/users, the headers will be as follows:

GET /users
Host: my-api.com
Origin: https://my-site.com

The server checks the Origin header and, if it supports cross-domain requests, adds a special HTTP header Access-Control-Allow-Origin to the response.

# Private API
Access-Control-Allow-Origin: https://my-site.com

# Public API
Access-Control-Allow-Origin: *

The value of this header will be the permitted source (Origin). In our case, it should be a site, https://my-site.com, if the back-end is private, or the special character *, if the back-end is public and allows making requests to anyone.

Cross-Origin Resource Sharing

That is, the browser is an intermediary between the JavaScript code and the back-end. It adds the Origin header with the correct value to each request and checks for the Access-Control-Allow-Origin header in the response. If the header is there and its value is correct, the original request will be executed and the JavaScript code will receive its result, otherwise there will be a CORS error.