Helps to understand the importance and involvement of CORS configuration in any web interface
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.
Why will the browser block the communication?
Its browser security features. It will do so if the request is coming from an origin different from that of the client. The additional headers included as a result of CORS is a way of telling the client that it can make use of the response that it received.
These are the headers that the server sends back in its response.
Access-Control-Allow-Origin: https://geekflare.com, or that the origin does not matter – Access-Control-Allow-Origin: *.
Here is an example of what the response will look like
HTTP/1.1 204 No Content
Access-Control-Allow-Headers: Content-Type, Accept
Date: Sat, 16 Nov 2019 11:41:08 GMT+1
Request Headers :
Here are the headers that a client’s request should contain in order to make use of the CORS mechanism.
Access-Control-Request-Headers: This is used in a preflight request to indicate the HTTP headers that will be used to make the request.
Here is an example of what a request will look like
curl -i -X OPTIONS localhost:3001/api \
-H 'Access-Control-Request-Method: GET' \
-H 'Access-Control-Request-Headers: Content-Type, Accept' \
-H 'Origin: http://localhost:3000'
Preflight Requests :
What is a Preflight request?
Preflight requests happen when the client has to send a preflight request before the main request. The preflight request is more of a probe to determine if the server supports the main request that’s about to be made. When positive confirmation is obtained, the main request is then sent.
When a request is not a preflight request, it is called a simple request.
CORS relaxes the policy so that your browser can access the resources you want it to. Understanding what it is, why it’s essential, and how to set it up will help in figuring out the issues you might face as you build your web applications.