Node.js Course
Node.js
/
Intermediate

CORS

Definition

Cross-Origin Resource Sharing. A browser security mechanism that restricts web pages from making HTTP requests to a different domain than the one that served the web page.

Explain Like I'm New

Imagine you log into your bank at `bank.com`. Then you visit an evil hacker site at `evil.com`. The hacker site runs a hidden script: `fetch('bank.com/transfer-money')`. CORS is the bouncer at the bank's door. The bouncer sees the request is coming from `evil.com`, blocks it, and screams 'CORS ERROR!' in the hacker's browser console.

Real World Example

If you build a React app on `localhost:3000` and try to fetch data from your Node API on `localhost:8080`, your browser will block it with a CORS error. You must tell the Node backend to explicitly allow traffic from `localhost:3000`.

Common Use Cases

  • •Securing public APIs
  • •Connecting separate frontend and backend servers

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Does the Node.js server throw the CORS error, or does the Browser?

intermediate

  • What is an OPTIONS Preflight request?

Flash Cards

Question

Who throws the error?

Click to reveal answer
Answer

The BROWSER throws the error! Postman and Curl do not care about CORS. Browsers enforce CORS to protect the user.

Question

What is an OPTIONS Preflight?

Click to reveal answer
Answer

Before the browser sends a dangerous POST or DELETE request, it sends a tiny scout request called an `OPTIONS` ping to the server asking: 'Are you going to allow this?'. If the server replies 'Yes', the browser then sends the real POST request.