XMLHttpRequest is APIwhich is used by JS scripts to send requests to the server. Quite often, it is used to create interactive pages that load data on the fly without reloading the page. Using such API quite popular, but for security reasons, you can only send requests within the same domain by default. This security is organized through the use of CORSwhich limits all cross-site HTTP requests.
To indicate the address from which the request was made, the header is used
Origin... This title looks something like this:
GET /example/ HTTP/1.1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 Accept: application/json, text/plain, */* Referer: http://for.example.com/ Origin: http://for.example.com
The response from the server to such a request may be something like this:
HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Date: Sat, 01 Jan 2001 00:00:00 GMT Server: nginx Content-Length: 35 Connection: keep-alive Access-Control-Allow-Origin: http://for.example.com
In this case, the title
Access-Control-Allow-Origin allows requests from the specified address and denies from other addresses. It is because of the absence of such a header that a problem can arise with cross-domain requests. How the header works
Access-Control-Allow-Origin is to prohibit or allow the use of the resources of one site within other sites. Lack of title
Access-Control-Allow-Origin is equivalent to indicating a ban on the use of resources.
There are several ways to solve the problem:
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization"); header("Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS");
In this case, requests will be allowed from any address without any protection. Instead of the symbol
* you can specify the address of the site from which requests will be allowed, in the form
Header add Access-Control-Allow-Origin "*" Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
To allow access to several addresses, they must be specified on a new line, for example, like this:
Header add Access-Control-Allow-Origin "http://some.for.example.com" Header add Access-Control-Allow-Origin "http://for.example.com" Header add Access-Control-Allow-Origin "http://example.com"