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 a Preflight request in CORS? 🤨
According 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.
The preflight request is automatically issued by the browser and frontend devs don’t do the options call.
OPTIONS call appears when the request is qualified as "to be preflighted".
How does the Preflight request work?
Before sending a POST request to the server, you will ask the server for a POST request.
OPTIONS /resource/foo Access-Control-Request-Method: POST Access-Control-Request-Headers: origin, x-requested-with Origin: https://foo.bar.org
If the server allows it, then it will respond to the preflight request with an OPTIONS response header, which lists
HTTP/1.1 204 No Content Connection: keep-alive Access-Control-Allow-Origin: https://foo.bar.org Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE Access-Control-Max-Age: 86400
Lets take an example, you are working on a blog website 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 the blog website 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 the firefox/chrome browser it will indicate whether this was a same-origin request or not.
A quick example of cross-origin request headers:
cross-site tells the request initiator and the server hosting the resource have a different site.
API. subdomain will cut your network traffic in half.
Top comments (0)