Interview frequency: …
Short answer
CORS is a browser security mechanism that prevents external sites from reading your data; a Preflight is an OPTIONS request the browser sends before the actual request to check whether it is allowed.
Explanation
Browsers require the server's explicit approval when JavaScript tries to read a response from another origin. If the request contains non-standard headers (such as Authorization), or a non-simple method (such as PUT, DELETE, or POST with JSON), the browser first sends an OPTIONS (Preflight) request. The server must respond with appropriate Access-Control-Allow-Origin and Access-Control-Allow-Methods headers.
Code example
import cors from "cors";
app.use(cors({
origin: "https://my-frontend.com",
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true
}));Common mistakes
- Setting Access-Control-Allow-Origin: * while enabling credentials: true, which browsers reject for security reasons.