DEV Community

Cover image for What is CORS πŸ€”?
Kiran Kamath
Kiran Kamath

Posted on

What is CORS πŸ€”?

  • Ever faced an issue while making a fetch call saying that it is a CORS issue.
    This is probably due to client saying that request to server belonging to another domain could not be made.
    CORS actually stands for Cross Origin Resource Sharing.

  • By default, in all browsers request made from a client having domain to server belonging to same origin is allowed i.e. Same Origin requests are allowed.
    example:- request from www.xyz.com/create to server having origin as www.xyz.com is allowed by browser.

  • This is done to prevent unknown source from making a request and corrupting the system i.e. for security purposes.

  • But if the browser itself allows a client from another origin to make request, based on the headers provided by server , then we can make this cross origin requests.

  • Every request made from client end has a header property called as Origin.

  • When client sends the request , server will send a header in response stating what all cross origin requests are allowed by specifying it in the property :- Access-Control-Allow-Origin.

  • So the browser will check the response from server and checks if the property Access-Control-Allow-Origin has the origin name specified in it.

  • In case if the request is not a normal request i.e. is request type is not GET or POST , then a special request is sent from the server first called as Preflight Request.
    So this preflight request sent from server will have only headers and no resources , it contains headers such as Access-Control-Allow-Origin , Access-Control-Allow-Methods.

  • Based on this request from the server , the client will make a new request for resources to the server.

Top comments (0)