7.6 CORS(跨域资源共享)配置
FastAPI CORS Configuration Tutorial for Python Beginners: Easy Step-by-Step Guide
A simple, hands-on guide to configure CORS in FastAPI for Python beginners. Learn how to allow cross-origin requests with clear examples, analogies, and easy-to-follow steps to build your first secure web API.
Configuring CORS in FastAPI: A Beginner-Friendly Tutorial
Welcome to this easy guide on setting up CORS (Cross-Origin Resource Sharing) in FastAPI! If you're new to web development and just learned Python basics, you're in the right place. This tutorial will help you understand and implement CORS with simple explanations and working examples.
What is CORS? Let's Use an Analogy
Imagine you have a house (your FastAPI server) and you want to let friends from other neighborhoods (different websites) visit. But for safety, you only allow friends from certain neighborhoods to enter. CORS is like your house rules—it tells web browsers which other websites can talk to your server.
In tech terms, CORS is a security feature that controls how your FastAPI app responds to requests from different domains or origins. Without it, browsers block these requests by default, which helps prevent malicious attacks.
Why Do We Need CORS in FastAPI?
When you build a web app, you might have a backend (like FastAPI) and a frontend (like a website running on a different address). CORS lets them communicate safely. For example, if your frontend is on http://localhost:3000 and your backend is on http://127.0.0.1:8000, you need to configure CORS so they can exchange data.
Prerequisites
- Basic Python knowledge (e.g., functions, imports).
- FastAPI and Uvicorn installed. If not, run in your terminal:
pip install fastapi uvicorn - A code editor (like VS Code or even Notepad).
Let's Dive In: Your First CORS Setup
Follow along step-by-step to create a working FastAPI app with CORS. We'll keep it super simple!
Step 1: Create a New Python File
Open your editor and create a file named main.py. This will be our main application file.
Step 2: Write the FastAPI App with CORS
Copy this code into main.py:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# Create the FastAPI app
app = FastAPI()
# Define allowed origins—like listing trusted friends' neighborhoods
origins = [
"http://localhost:3000", # Allow your frontend running on localhost:3000
]
# Add CORS middleware to the app
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # Only origins in the list can access
allow_credentials=True, # Allow cookies or login details (optional)
allow_methods=["*"], # Allow all HTTP methods: GET, POST, etc.
allow_headers=["*"], # Allow all headers in requests
)
# Add a simple endpoint to test
@app.get("/")
def read_root():
return {"message": "Hello from FastAPI with CORS! You did it!"}
Step 3: Run Your App
Save the file and run it in your terminal:
uvicorn main:app --reload
You'll see output like:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
This means your FastAPI server is live at http://127.0.0.1:8000.
Step 4: Test Your Success Moment!
Open your web browser and go to http://127.0.0.1:8000. You should see:
{"message": "Hello from FastAPI with CORS! You did it!"}
🎉 Congratulations! Your basic FastAPI app is working.
Now, let's test if CORS is configured correctly. This is where the magic happens!
Step 5: Test CORS with a Simple Frontend
Create a new file named test.html in the same folder as main.py, and copy this HTML code:
<!DOCTYPE html>
<html>
<body>
<h2>Testing CORS in FastAPI</h2>
<p>Open the browser console (Press F12 and go to Console tab) to see the result.</p>
<script>
// Try to fetch data from your FastAPI server
fetch('http://127.0.0.1:8000/')
.then(response => response.json())
.then(data => console.log('Success! Response:', data))
.catch(error => console.log('Error:', error));
</script>
</body>
</html>
Serve this HTML file from http://localhost:3000 to simulate a different origin. In a new terminal, run:
python -m http.server 3000
Now, open your browser and go to http://localhost:3000/test.html. Check the console (F12 → Console). You should see:
Success! Response: {message: "Hello from FastAPI with CORS! You did it!"}
🌟 Amazing! CORS is working—your frontend can talk to your FastAPI server. If you get an error, double-check that the FastAPI server is running and the origins match.
Customizing CORS
You can easily tweak the CORS settings:
- To allow all origins (not recommended for production, but good for testing): change
originsto["*"]. - To add more allowed domains: just list them in the
originsarray.
Example:
origins = [
"http://localhost:3000",
"https://mywebsite.com", # Add another trusted origin
]
Summary
You've successfully configured CORS in FastAPI! Here's what you learned:
- CORS is like setting guest rules for your web server.
- FastAPI makes it easy with
CORSMiddleware. - You can control which domains are allowed to access your API.
Next Steps
- Experiment by adding more endpoints to your FastAPI app.
- Try changing the
allow_methodsorallow_headersto see how it affects requests. - Check out the FastAPI documentation for advanced options.
Keep practicing, and soon you'll be building full web apps with confidence!