Postman Works, The Browser Says NO. CORS Vs A Weather API

Solvedapicorsjavascript6 replies · 108 views · started
Accepted solution by Malik Tanaka — been there man requests with Authorization headers or Content Type: application/json trigger a preflight OPTIONS request. the server must…
  1. ok weird one im builidng a React app on localhost:5173 and trying to fetch data from a weather API, postman returns the data perfectly... the browser gives me this:

    The console says the request has been blocked by CORS policy, no Access-Control-Allow-Origin header is present. i dont understand why the same request works in one tool and not the other. Is this something i fix in my code or on teh API side? A plain explanation would honestly help as much as the fix itself. thx in advance!!

    2
  2. wait what status code does the OPTIONS preflight request get in teh Network tab?

    3 1 helpful
  3. yeah so its a third party, a weather API. Their docs mention a server-side key, which Ive been putting in frontend code..... oops. sorry for the wall of text lol

    2 0 helpful
  4. If you send cookies or use credentials: 'include', the server cannot use *. It must echo the exact origin and send Access-Control-Allow-Credentials: true. That's why a wildcard sometimes 'doesn't work'.

    4 0 helpful
  5. Accepted solution

    been there man requests with Authorization headers or Content-Type: application/json trigger a preflight OPTIONS request. the server must respond to it with a 2xx status plus Access-Control-Allow-Methods and Access-Control-Allow-Headers listing what u send. many servers return 404 or 401 to OPTIONS, which fails teh whole thing.

    0 2 helpful
  6. wait what sometimes its simpler to host the frontend and API on teh same origin under different paths. No CORS at all, fewer headers to maintain.

    0 5 helpful
  7. @malikt624 Moved the a weather API call to a small serverless function sooo the secret key stays private. No CORS problem and a security hole closed. thx!

    party

    0 13 helpful

Reply to this topic

Sign in or create an account to reply.