What is CORS and why can't I just disable it?
poze 4 months ago235 gadeen
My frontend gets "blocked by CORS policy" errors. A Stack Overflow answer says to add Access-Control-Allow-Origin: *. Is that safe?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.