CORS là cơ chế browser bảo vệ user — server phải opt-in cho phép cross-origin requests.
Preflight mechanism: browser tự động gửi OPTIONS request trước khi gửi request thật nếu là preflighted request (method không phải GET/POST/HEAD, hoặc header không phải simple header như Content-Type: application/json).
Simple requests (GET với simple headers) không cần preflight.
Cấu hình production đúng: cors({ origin: ['https://app.example.com'], methods: ['GET','POST','PUT','PATCH','DELETE'], allowedHeaders: ['Content-Type','Authorization'], credentials: true }) — credentials: true bắt buộc khi gửi cookies/Authorization header.
Quan trọng: khi credentials: true, origin KHÔNG được là * — phải liệt kê explicit.
Debug tips:
- kiểm tra response header
Access-Control-Allow-Origintrong DevTools Network tab, credentials: truenhưng server trả*→ browser chặn,- đặt
cors()TRƯỚC routes để OPTIONS preflight được handle
Lưu ý: CORS là browser enforcement — Postman/curl không bị chặn, chỉ browser mới bị.
CORS is a browser security mechanism — the server must opt in to allow cross-origin requests.
Preflight mechanism: the browser automatically sends an OPTIONS request before the actual request if it is preflighted (non-simple methods like PUT/DELETE, or non-simple headers like Content-Type: application/json).
Simple requests (GET with simple headers) don't require a preflight.
Correct production config: cors({ origin: ['https://app.example.com'], methods: ['GET','POST','PUT','PATCH','DELETE'], allowedHeaders: ['Content-Type','Authorization'], credentials: true }) — credentials: true is required when sending cookies or Authorization headers.
Important: when credentials: true, the origin CANNOT be * — you must specify it explicitly.
Debug tips:
- check the
Access-Control-Allow-Originresponse header in DevTools Network tab, credentials: truebut server returns*→ browser blocks it,- place
cors()BEFORE routes so OPTIONS preflight requests are handled
Pitfall: CORS is enforced by browsers only — Postman, curl, and server-to-server requests are not affected.