Understand HTTP CORS Request
You always used HTTP methods like GET/POST/PUT/DELETE, there is one more methods called OPTIONS which used to execute prior to GET/POST/PUT/DELETE methods.
What is CORS đ¤
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
What is Preflight request in CORS? đ¤¨
Accoridng to MDN Docs , A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.
It is an OPTIONS  request, using three HTTP request headers: Access-Control-Request-Method , Access-Control-Request-Headers  , and the Origin  header.
Preflight request automatically issued by browser and frontend devs doesnât do the options call.
OPTIONS call appears when request is qualified as "to be preflighted".
How does the Preflight request works?
Before sending a POST request to server, you will ask the server for POST request.
OPTIONS /resource/fooAccess-Control-Request-Method: POSTAccess-Control-Request-Headers: origin, x-requested-withOrigin: https://foo.bar.org
If the server allows it, then it will respond to the preflight request with an OPTIONS response header, which lists POST
:
HTTP/1.1 204 No ContentConnection: keep-aliveAccess-Control-Allow-Origin: https://foo.bar.orgAccess-Control-Allow-Methods: POST, GET, OPTIONS, DELETEAccess-Control-Max-Age: 86400
Lets take an example, you are working on a blog webiste blog.suprabha.me and your API is on api.blog.suprabha.me. Itâs really nice and easy to understand to see the prefix of blog webiste is âapiâ.
As you can see the the API(api.blog.suprabha.me) and the origin( blog.suprabha.me ) are different, also the hostname is different.
Port and Protocol also follow the same logic as hostname. So if there is any differences in hostname, port, protocol request executed on the page will require a CORS request.
If you notice the header `sec-fetch-site` is attached to any XHR request in firefox/chrome browser which will indicate whether this was a same-origin request or not.
Quick example for cross origin request headers:
Sec-Fetch-Site: cross-site
cross-site tells the request initiator and the server hosting the resource have a different site.
If you try to write proxy using node or use any services like Cloudfare to proxy your application, which create an alias to the api which routes api.blog.suprabha.me to blog.suprabha.me/api and moving over the JavaScript clients using the api.
 subdomain will cut your network traffic in half.