What about Preflight requests?
Access-Control-Allow-Origin header is required on all valid CORS responses, but there are certain types of requests (such as DELETE or PUT) for which this header alone is not enough.
For these types of requests, the browser needs to ask for server’s permission before making the actual request, using a preflight request (OPTIONS request).
A preflight request contains information like which HTTP method is used, as well as if any custom HTTP headers are present. The preflight gives the server a chance to examine what the actual request will look like before it is made.
The server receiving the preflight request must respond with CORS headers indicating whether the actual request should be permitted.
Besides Access-Control-Allow-Origin header the server should respond with the following CORS headers:
Access-Control-Allow-Methods - specifies the allowed HTTP methods
Access-Control-Allow-Headers - specifies the allowed headers
If the response to the preflight request is successful, the browser will go ahead and send the actual request to the server. If the preflight request fails or the server's response does not allow the actual request, the browser will block the subsequent request, and an error will be thrown.
In conclusion, CORS headers allow web servers to control which domains can access their resources, ensuring a secure and controlled environment for cross-origin requests. It helps prevent unauthorized access to sensitive data and reduces the risk of data breaches. It is also a straightforward way to overcome browsers default Same Origin Policy Restrictions.