Trung BìnhPython iconPython

CORS là gì? Cấu hình trong FastAPI như thế nào?

CORS (Cross-Origin Resource Sharing) là browser security mechanism ngăn requests từ origin khác.

Backend phải whitelist các origins được phép.

python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",  # Vite dev server
        "https://yourapp.com",    # Production
    ],
    allow_credentials=True,  # Cần cho cookies/auth headers
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["Authorization", "Content-Type"],
)

Pitfall: allow_origins=["*"] với allow_credentials=True sẽ bị browser từ chối — phải liệt kê explicit origins.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python