Video

What Is CORS? in 30 Seconds

Your API returns 200. Your browser still refuses to give you the data. That's
CORS — and it's probably not doing what you think.

WHAT AN ORIGIN IS
scheme + host + port. All three must match.

http://localhost:3000 ← your frontend
http://localhost:8000 ← your API

Same machine, same host, different port. Different origin.

WHAT ACTUALLY HAPPENS
This is the part worth understanding: the request went out. The server
received it, ran your handler, and sent back 200 OK. Nothing was "blocked"
on the network.

The browser then checked the response for CORS headers, didn't find
permission for your origin, and refused to hand the response to your
JavaScript. The failure happens in the browser, after a successful request.

THE FIX IS ON THE SERVER
You cannot fix CORS from the frontend. Adding `Access-Control-Allow-Origin`
to your fetch() headers does nothing — it's a *response* header, sent by the
server:

Access-Control-Allow-Origin: http://localhost:3000

Set that on the API, and the browser lets the response through.

Some requests also trigger a preflight: the browser sends an `OPTIONS`
request first to ask whether the real one is permitted. That happens for
non-simple methods, custom headers, and certain content types.

CORS IS NOT AUTHENTICATION
This is the one that causes real damage. CORS only restrains browsers.

curl http://localhost:8000 # completely unaffected

So is Postman, so is any server-side client, so is any attacker not using a
browser. CORS protects your *users* from a malicious site reading their data
with their credentials. It does not protect your API. Authentication and
authorization are separate jobs.

And avoid `Access-Control-Allow-Origin: *` when credentials are involved —
browsers reject that combination anyway, and reaching for it usually means
reaching past a real fix.

—
#Astmation — #software #systems, #automation, and #AI-powered #applications.
Build. Automate. Evolve.
https://astmation.com/

#Shorts #CORS #WebDevelopment #JavaScript #API #Browser #WebSecurity #Frontend #BackendDevelopment #HTTP


Watch on YouTube

Back to videos