python
config_error
ai_generated
true
TypeError: 'CORSMiddleware' object is not callable
ID: python/fastapi-cors-middleware-error
80%Fix Rate
88%Confidence
0Evidence
2024-05-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
FastAPI中CORSMiddleware未正确添加到应用,导致被当作可调用对象处理。
generic中文
FastAPI中CORSMiddleware未正确添加到应用,导致被当作可调用对象处理。
Workarounds
-
95% success 使用add_middleware正确添加CORS中间件
from fastapi.middleware.cors import CORSMiddleware; app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])
-
90% success 使用Starlette的CORSMiddleware并手动添加
from starlette.middleware.cors import CORSMiddleware; app.add_middleware(CORSMiddleware, allow_origins=['*'])
Dead Ends
Common approaches that don't work:
-
直接导入CORSMiddleware并作为装饰器使用
90% fail
CORSMiddleware是类,需要实例化。
-
在路由中使用CORSMiddleware作为依赖项
80% fail
依赖项需要可调用对象。