Why does it work when directly accessed in the browser?
When you paste the URL directly into the browser’s address bar and hit enter, it’s considered a non-scripted request (direct navigation request). Since it’s not an AJAX request, the browser does not enforce CORS checks.
✅ Why does it fail in React (or any frontend JavaScript app)?
In a React app, when you use fetch()
or XMLHttpRequest
to make an AJAX request, it is a cross-origin request if the frontend and backend are running on different origins (different protocol, domain, or port). The browser enforces CORS policy in this case, blocking the request unless the backend explicitly allows it by setting proper Access-Control-Allow-Origin
headers.
✅ Why does it work from the backend (server-to-server)?
CORS is a browser-enforced security feature, meaning it only applies when a browser makes the request. If a backend server (e.g., a Node.js, PHP, or Python script) makes the request to another server, there is no CORS check because the request happens in a non-browser environment.
Final Explanation (Refined)
- Direct Browser Request (URL pasted in the browser) → Works ✅
- No CORS enforcement because it’s a non-scripted navigation request.
- React App (AJAX Fetch/XHR Request) → Blocked by CORS ❌
- Browser enforces CORS when making cross-origin requests from JavaScript.
- Backend-to-Backend Request → Works ✅
- No browser is involved, so CORS does not apply.
This is exactly why the server needs to handle CORS when serving responses to browsers but doesn’t need to worry about it when communicating with other servers.