Careeroza
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.
| Page | Calls | Same origin? |
|---|---|---|
| https://shopease.in | https://shopease.in/api/products | Yes |
| https://shopease.in | https://api.shopease.in/products | No (different host) |
| http://localhost:5173 | http://localhost:8080/api | No (different port) |
| http://shopease.in | https://shopease.in/api | No (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 CreatedNote
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.