CORS

  1. What is CORS (Cross-Origin Resource Sharing)

  2. Why we need it?

  3. How to deal with CORS issue?


What is CORS?

CORS stands for Cross-Origin Resource Sharing. Browsers are Same origin policy and you can fetch data from script tag or image by default. CORS is applied when you try to hit the api endpoint by using XMLHttpRequest.

Same origin policy

Same origin policy allows us to prevents server from being accessed by unknown clients. XMLHttpRequest and Fetch follow the same-origin policy. You probably have experience to see the situation that you get CORS problem even the server gets a request from the client while sending HTTP request through Ajax. It is because server did response but you can not have access right to see the data due to Same origin policy.

How we deal with CORS?

Preflight

"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain. Preflight request is anOPTIONS request and sent to check allowed origin and HTTP method by using HTTP request headers: Access-Control-Request-Method and Access-Control-Request-Headers, and the Origin header.

Request

OPTIONS /resource/foo 
Access-Control-Request-Method: DELETE 
Access-Control-Request-Headers: origin, x-requested-with
Origin: https://foo.bar.org

Response

HTTP/1.1 200 OK
Content-Length: 0
Connection: keep-alive
Access-Control-Allow-Origin: https://foo.bar.org
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400

https://developer.mozilla.org/en-US/docs/Glossary/preflight_request

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
https://www.w3.org/TR/cors/
https://developer.mozilla.org/ja/docs/Web/HTTP/HTTP_access_control

results matching ""

    No results matching ""