Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

What is CORS, and how would you fix a CORS error?

Browsers enforce the same-origin policy: a page at one origin — scheme, host, and port together — cannot read a response from a different origin unless that server allows it. CORS is the mechanism a server uses to grant that permission through response headers.

Simple requests — a GET or POST with a small set of allowed headers — are sent immediately, and the browser checks Access-Control-Allow-Origin on the response before letting JavaScript read it. Anything else triggers a preflight: the browser first sends an OPTIONS request asking whether the real request is permitted.

How to fix it, in order:

  • The fix belongs on the server. Nothing you write in the browser can grant your own permission — that is the entire point.
  • Set Access-Control-Allow-Origin to the specific origin, and Access-Control-Allow-Methods and Access-Control-Allow-Headers to cover what the client actually sends.
  • Make sure the server answers OPTIONS with a 2xx and no body. A preflight hitting an auth middleware that returns 401 is an extremely common cause.
  • If you need cookies, set Access-Control-Allow-Credentials: true — and note that you may not use * for the origin in that case.

Note: A proxy in your dev server is a legitimate local workaround, but say plainly that it is not a production fix. And a CORS error never means the request was blocked from being sent — it means the response was blocked from being read, so the server has already done the work.

All Front end Development interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as