CORS and Preflight Requests

Same Origin

An origin is scheme + host + port. http://localhost:5173 (React) and http://localhost:8080 (API) are different origins. Browsers block JavaScript from reading responses from another origin unless that server allows it with CORS (Cross-Origin Resource Sharing) headers.

PageCallsSame origin?
https://shopease.inhttps://shopease.in/api/productsYes
https://shopease.inhttps://api.shopease.in/productsNo (different host)
http://localhost:5173http://localhost:8080/apiNo (different port)
http://shopease.inhttps://shopease.in/apiNo (different scheme)

The Preflight

For "non-simple" requests (JSON body, an Authorization header, PUT/DELETE...) the browser first sends an OPTIONS preflight request to ask permission. Only if the answer allows it does it send the real request.

Browser (localhost:5173)                         API (localhost:8080)
  OPTIONS /api/orders
  Origin: http://localhost:5173
  Access-Control-Request-Method: POST
  Access-Control-Request-Headers: authorization,content-type  --->
                                <---  200  Access-Control-Allow-Origin: http://localhost:5173
                                           Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
                                           Access-Control-Allow-Headers: authorization,content-type
                                           Access-Control-Allow-Credentials: true
  POST /api/orders  (the real request, with Bearer token) --->
                                <---  201 Created

Note

Note: CORS is enforced by the browser, to protect users. It is not an API protection: curl, Postman and other servers ignore it. Your API still needs authentication and authorization on every endpoint.