Skip to content

⚜ (✖️-🇨🇳 ℹ 🤝)

⚜ ⚖️ "✖️-🇨🇳 ℹ 🤝" 🔗 ⚠ 🕐❔ 🕸 🏃‍♂ 🖥 ✔️ 🕸 📟 👈 🔗 ⏮️ 👩‍💻, & 👩‍💻 🎏 "🇨🇳" 🌘 🕸.

🇨🇳

🇨🇳 🌀 🛠️ (http, https), 🆔 (myapp.com, localhost, localhost.tiangolo.com), & ⛴ (80, 443, 8080).

, 🌐 👫 🎏 🇨🇳:

  • http://localhost
  • https://localhost
  • http://localhost:8080

🚥 👫 🌐 localhost, 👫 ⚙️ 🎏 🛠️ ⚖️ ⛴,, 👫 🎏 "🇨🇳".

🔁

, ➡️ 💬 👆 ✔️ 🕸 🏃 👆 🖥 http://localhost:8080, & 🚮 🕸 🔄 🔗 ⏮️ 👩‍💻 🏃 http://localhost (↩️ 👥 🚫 ✔ ⛴, 🖥 🔜 🤔 🔢 ⛴ 80).

⤴️, 🖥 🔜 📨 🇺🇸🔍 OPTIONS 📨 👩‍💻, & 🚥 👩‍💻 📨 ☑ 🎚 ✔ 📻 ⚪️➡️ 👉 🎏 🇨🇳 (http://localhost:8080) ⤴️ 🖥 🔜 ➡️ 🕸 🕸 📨 🚮 📨 👩‍💻.

🏆 👉, 👩‍💻 🔜 ✔️ 📇 "✔ 🇨🇳".

👉 💼, ⚫️ 🔜 ✔️ 🔌 http://localhost:8080 🕸 👷 ☑.

🃏

⚫️ 💪 📣 📇 "*" ("🃏") 💬 👈 🌐 ✔.

✋️ 👈 🔜 🕴 ✔ 🎯 🆎 📻, 🚫 🌐 👈 🔌 🎓: 🍪, ✔ 🎚 💖 📚 ⚙️ ⏮️ 📨 🤝, ♒️.

, 🌐 👷 ☑, ⚫️ 👻 ✔ 🎯 ✔ 🇨🇳.

⚙️ CORSMiddleware

👆 💪 🔗 ⚫️ 👆 FastAPI 🈸 ⚙️ CORSMiddleware.

  • 🗄 CORSMiddleware.
  • ✍ 📇 ✔ 🇨🇳 (🎻).
  • 🚮 ⚫️ "🛠️" 👆 FastAPI 🈸.

👆 💪 ✔ 🚥 👆 👩‍💻 ✔:

  • 🎓 (✔ 🎚, 🍪, ♒️).
  • 🎯 🇺🇸🔍 👩‍🔬 (POST, PUT) ⚖️ 🌐 👫 ⏮️ 🃏 "*".
  • 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 "*".
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def main():
    return {"message": "Hello World"}

🔢 🔢 ⚙️ CORSMiddleware 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑.

📄 ❌ 🐕‍🦺:

  • allow_origins - 📇 🇨🇳 👈 🔜 ✔ ⚒ ✖️-🇨🇳 📨. 🤶 Ⓜ. ['https://example.org', 'https://www.example.org']. 👆 💪 ⚙️ ['*'] ✔ 🙆 🇨🇳.
  • allow_origin_regex - 🎻 🎻 🏏 🛡 🇨🇳 👈 🔜 ✔ ⚒ ✖️-🇨🇳 📨. ✅ 'https://.*\.example\.org'.
  • allow_methods - 📇 🇺🇸🔍 👩‍🔬 👈 🔜 ✔ ✖️-🇨🇳 📨. 🔢 ['GET']. 👆 💪 ⚙️ ['*'] ✔ 🌐 🐩 👩‍🔬.
  • allow_headers - 📇 🇺🇸🔍 📨 🎚 👈 🔜 🐕‍🦺 ✖️-🇨🇳 📨. 🔢 []. 👆 💪 ⚙️ ['*'] ✔ 🌐 🎚. Accept, Accept-Language, Content-Language & Content-Type 🎚 🕧 ✔ 🙅 ⚜ 📨.
  • allow_credentials - 🎦 👈 🍪 🔜 🐕‍🦺 ✖️-🇨🇳 📨. 🔢 False. , allow_origins 🚫🔜 ⚒ ['*'] 🎓 ✔, 🇨🇳 🔜 ✔.
  • expose_headers - 🎦 🙆 📨 🎚 👈 🔜 ⚒ ♿ 🖥. 🔢 [].
  • max_age - ⚒ 🔆 🕰 🥈 🖥 💾 ⚜ 📨. 🔢 600.

🛠️ 📨 2️⃣ 🎯 🆎 🇺🇸🔍 📨...

⚜ 🛫 📨

👉 🙆 OPTIONS 📨 ⏮️ Origin & Access-Control-Request-Method 🎚.

👉 💼 🛠️ 🔜 🆘 📨 📨 & 📨 ⏮️ ☑ ⚜ 🎚, & 👯‍♂️ 200 ⚖️ 400 📨 🎓 🎯.

🙅 📨

🙆 📨 ⏮️ Origin 🎚. 👉 💼 🛠️ 🔜 🚶‍♀️ 📨 🔘 😐, ✋️ 🔜 🔌 ☑ ⚜ 🎚 🔛 📨.

🌅 ℹ

🌖 ℹ 🔃 ⚜, ✅ 🦎 ⚜ 🧾.

📡 ℹ

👆 💪 ⚙️ from starlette.middleware.cors import CORSMiddleware.

FastAPI 🚚 📚 🛠️ fastapi.middleware 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.