Bird
0
0

How can you combine TrustedHostMiddleware with CORS middleware in FastAPI to allow trusted hosts and cross-origin requests safely?

hard🚀 Application Q9 of 15
FastAPI - Middleware and Hooks
How can you combine TrustedHostMiddleware with CORS middleware in FastAPI to allow trusted hosts and cross-origin requests safely?
AAdd only TrustedHostMiddleware, CORS is not needed
BAdd TrustedHostMiddleware first, then CORSMiddleware with allowed origins
CAdd CORSMiddleware first, then TrustedHostMiddleware with allowed_hosts
DAdd only CORSMiddleware, TrustedHostMiddleware is redundant
Step-by-Step Solution
Solution:
  1. Step 1: Understand middleware order importance

    TrustedHostMiddleware should run before (outermost) CORSMiddleware to block untrusted hosts early.
  2. Step 2: Configure CORSMiddleware with allowed origins

    Add CORSMiddleware after TrustedHostMiddleware so that CORS headers are applied only to trusted hosts.
  3. Final Answer:

    Add TrustedHostMiddleware first, then CORSMiddleware with allowed origins -> Option B
  4. Quick Check:

    TrustedHostMiddleware (outer) before CORSMiddleware = C [OK]
Quick Trick: Order matters: TrustedHostMiddleware first, then CORSMiddleware [OK]
Common Mistakes:
MISTAKES
  • Reversing middleware order
  • Skipping TrustedHostMiddleware
  • Assuming CORS replaces host filtering

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes