</>
⌕
Mid #cors#same-origin-policy#preflight#security

CORS là gì? Preflight request hoạt động ra sao?

⚡ Trả lời nhanh

Same-origin policy chặn JS đọc response cross-origin; CORS là cơ chế server dùng header Access-Control-* để cho phép. Với request không đơn giản (method khác GET/POST/HEAD, header tùy chỉnh, JSON content-type), trình duyệt gửi OPTIONS preflight trước để hỏi server có cho phép không.

OPTIONS /api/items HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type, authorization

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, PUT
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600
  • Origin = scheme + host + port; chỉ cần khác một thành phần là cross-origin.
  • Gửi cookie cần credentials: "include" ở client và Allow-Credentials: true ở server; khi đó Allow-Origin không được là *.
  • Access-Control-Max-Age cache kết quả preflight, giảm số request.
🃏 Ôn bằng flashcard