Bird
0
0

Given this FastAPI code snippet, what will be the effect of the CORS middleware?

medium📝 component behavior Q13 of 15
FastAPI - Middleware and Hooks
Given this FastAPI code snippet, what will be the effect of the CORS middleware?
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"message": "Hello"}
AOnly requests from https://example.com with GET or POST methods are allowed
BAll origins and methods are allowed
CNo requests are allowed because allow_origins is too restrictive
DOnly GET requests from any origin are allowed
Step-by-Step Solution
Solution:
  1. Step 1: Analyze allow_origins and allow_methods

    allow_origins is set to ["https://example.com"], so only that origin is allowed. allow_methods includes GET and POST.
  2. Step 2: Determine request permissions

    Requests from other origins or methods not in GET/POST will be blocked by CORS policy.
  3. Final Answer:

    Only requests from https://example.com with GET or POST methods are allowed -> Option A
  4. Quick Check:

    allow_origins and allow_methods restrict access [OK]
Quick Trick: Check allow_origins and allow_methods lists carefully [OK]
Common Mistakes:
MISTAKES
  • Assuming allow_origins=["*"] when it is not
  • Ignoring allow_methods restrictions
  • Thinking all origins are allowed by default

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes