浏览器同源策略,Python FastAPI解决办法

app = FastAPI()
# 配置 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8080"],  # 允许来自这个地址的请求
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有的 HTTP 方法 (GET, POST, etc.)
    allow_headers=["*"],  # 允许所有的请求头
)

注意:如果后端出现错误,即使正确进行了上述配置,可能还是会报No 'Access-Control-Allow-Origin' header is present on the requested resource.错误。最好的办法就是先排除所有其他错误后,再解决同源策略问题。