CORS "No Access-Control-Allow-Origin header is present": the fix, and what not to do
The browser console shows: Access to fetch at 'https://api.example.com' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resour
The browser console shows:
Access to fetch at 'https://api.example.com' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What it means
Your browser asked a different origin for data, and that server did not say your origin is allowed. The browser blocked the response. The request usually reached the server. The browser refused to hand you the answer.
How to fix it
- Fix it on the server that owns the data, not in the frontend. Add an
Access-Control-Allow-Originheader for your app's exact origin. - Handle the preflight. For requests with custom headers or methods like PUT and DELETE, the browser first sends an
OPTIONSrequest. Return a 2xx with the allowed methods and headers. - If you send cookies, you need
Access-Control-Allow-Credentials: trueand a specific origin, not*. - Redirects and error pages often lack CORS headers. A 500 or a 301 can show up as a "CORS error" even though the real problem is somewhere else. Check the network tab for the true status.
The fix to avoid
Setting Access-Control-Allow-Origin: * together with credentials is rejected by browsers. Setting * on an API that returns private user data lets any website read it from your users' browsers. Allow the specific origins you trust.
Check it works
Open your app, make the request, and look in the network tab at the response headers. Then check the same API from another origin that should not be allowed. It should be blocked.
Same steps with the FAQ: https://proofforge.live/errors/no-access-control-allow-origin-header . To check your live app's CORS headers and other public exposures, run the free outside check at https://proofforge.live
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.