Bird
0
0

Which CORS middleware setup is correct?

hard🚀 Application Q15 of 15
FastAPI - Middleware and Hooks
You want your FastAPI backend to accept requests from two frontend domains: https://app1.example.com and https://app2.example.com. You also want to allow all HTTP methods and headers. Which CORS middleware setup is correct?
Aapp.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"])
Bapp.add_middleware(CORSMiddleware, allow_origins=["*"])
Capp.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["GET", "POST"], allow_headers=["Content-Type"])
Dapp.add_middleware(CORSMiddleware, allow_origins="https://app1.example.com,https://app2.example.com", allow_methods=["*"], allow_headers=["*"])
Step-by-Step Solution
Solution:
  1. Step 1: Set allow_origins correctly

    To allow two specific domains, use a list with both URLs as strings.
  2. Step 2: Allow all methods and headers

    Using ["*"] for allow_methods and allow_headers allows all HTTP methods and headers.
  3. Step 3: Check for syntax correctness

    app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"]) correctly uses a list for origins and lists with "*" for methods and headers.
  4. Final Answer:

    app.add_middleware(CORSMiddleware, allow_origins=["https://app1.example.com", "https://app2.example.com"], allow_methods=["*"], allow_headers=["*"]) -> Option A
  5. Quick Check:

    List origins + wildcard methods/headers [OK]
Quick Trick: Use list for origins and ["*"] to allow all methods/headers [OK]
Common Mistakes:
MISTAKES
  • Passing origins as a single comma string
  • Using allow_methods with limited verbs instead of wildcard
  • Setting allow_origins to ["*"] when only specific domains needed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes