What is CORS and why can't I just disable it?

posée 4 months ago238 vuesen

4

My frontend gets "blocked by CORS policy" errors. A Stack Overflow answer says to add Access-Control-Allow-Origin: *. Is that safe?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

1 réponse

5
✓
✓ Réponse acceptée

First, what CORS is: browsers enforce the same-origin policy, meaning JavaScript on site-a.com can't read responses from api-b.com unless api-b.com explicitly allows it with CORS headers. It protects users: a malicious site can't read data from your bank's API using your logged-in cookies.

CORS is not a server-side protection. curl or Postman ignore it completely. It only controls what *browsers* let other websites' scripts read.

About Access-Control-Allow-Origin: *: - It's fine for truly public, unauthenticated APIs (public data, open endpoints). - It can't be combined with credentials (cookies) anyway, since browsers reject * + Allow-Credentials: true. - Don't "fix" it by reflecting any Origin back with credentials allowed. That reopens the hole CORS closes.

For your own frontend: allow-list the exact origins (https://app.example.ht, http://localhost:5173 in dev only), or put the frontend and API on the same origin (reverse proxy or a dev-server proxy), which makes CORS unnecessary.

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.