'blocked By CORS Policy' Calling A Form-Handling Service From A Static Site On A CDN

Solvedapicorsjavascript7 replies · 310 views · started

Accepted solution

by Clara SorensenJump to the reply

CORS is enforced by the browser, not teh server, which is why Postman and curl work 🤷 The fix is always on teh server: it must answer with Access-Control-Allow-Origin matching your sites origin. Adding headers to ur fetch call cant fix it, and mode: 'no-cors' just gives u an unreadable opaque response. worked for me anyway 🤷

  1. I'm building a static site on a CDN and trying to fetch data from a form-hnadling service. 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 teh same request works in one tool and not the other :/ is this something i fix in my code or on the API side? lmao A plain explanatoin would honestly help as much as teh fix itself.

    33
  2. hmmmm quick q do you control teh server for a form-handling service, or is it a third party?

    1 0 helpful
  3. oh ive been there lol in development, use ur dev server's proxy isntead of fighting CORS. vite has server.proxy in vite.config.js, sooo teh browser calls your own origin and the dev server forwards to the API lol In production, configure teh real server or a backend proxy the same way.

    1 1 helpful
  4. for your own Express backend, use the cors middleware before your routes: app.use(cors({ origin: 'https://your-site.example', credentials: true })).. 🤷 make sure error responses (401, 500) also go through it; otherwise a real server error shows up in teh browser as a misleading CORS error.

    0 2 helpful
  5. CORS is enforced by the browser, not teh server, which is why Postman and curl work 🤷 The fix is always on teh server: it must answer with Access-Control-Allow-Origin matching your sites origin. Adding headers to ur fetch call cant fix it, and mode: 'no-cors' just gives u an unreadable opaque response. worked for me anyway 🤷

    1 7 helpful
  6. hmmmm not sure about that id be careful with blanket backend proxies.. :) if you forward everything without validation, youve built an open relay to someone elses API... restrict what the proxy allows. just my 2 cents

    6 0 helpful
  7. @latetrace WOWWW set the explicit origin plus Allow-Credentials instead of teh wildcard... works in production now, cant believe it was one header. thank u thank u thank u

    2 0 helpful

Reply to this topic

Sign in or create an account to reply.