why does a form-handling service reject my preflight request from a vue app on a static host??

Solvedapicorsjavascript10 replies · 266 views · started
Accepted solution by Clara — yeahhh for ur own Express backend, use the cors middleware before ur routes: app.use(cors({ origin: 'https://your site.example',…
  1. so annoyed rn im building a Vue app on a static host and trying to fetch data from a form-handling service. Postman returns the data perfectly. The browser gives me this:

    The console says teh request has been blocekd by CORS policy, no Access-Control-Allow-Origin header is present... i don't understand why teh 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.

    10
  2. Requests with Authorization headers or Content-Type: application/json trigger a prelfight 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 the whole thing.

    2 0 helpful
  3. respectfully disagree, i tried that and it made form-handling worse

    3 2 helpful
  4. @nina_kernel nah thats not it, service has nothing to do with it

    1 0 helpful
  5. yeahhh in development, use your dev servers proxy instead of fighting CORS, vite has server.proxy in vite.config.js, so the browser calls ur own origin and the dev server forwards to the API. In production, configure the real sevrer or a backend proxy the same way.

    1 4 helpful
  6. CORS is enforced by teh browser, not teh server, which is why Postman and curl work. The fix is always on the server: it must answer with Access-Control-Allow-Origin matching ur sites origin. adding headers to ur fetch call cant fix it, and mode: 'no-cors' just gives you an unreadable opaque response. lmk how it goes

    1 1 helpful
  7. Accepted solution

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

    lol

    0 8 helpful
  8. pro tip: write down what u change... i didnt and had to redo cors from scratch. @regex_wrangler156 did u ever fix it? worked for me anyway 🤷

    0 2 helpful
  9. wait what sometimes it's simpler to host teh frontend and API on teh same origin under different paths. no CORS at all, fewer headers to maintain.

    2 0 helpful
  10. @cthorne Moved teh a form-handling service call to a small serverless function sooo teh secret key stays private. No CORS problem and a security hole closed, thx!

    5 1 helpful

Reply to this topic

Sign in or create an account to reply.