使用FastAPI开发接口时,跨域调用报错如下:

1
Access to XMLHttpRequest at 'http://xxxxxxxxxx' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决方案:

1
2
3
4
5
6
7
8
9
10
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],#允许进行跨域请求的来源列表,*作为通配符
allow_credentials=True,#跨域请求支持cookie,默认为否
allow_methods=["*"],#允许跨域请求的HTTP方法
allow_headers=["*"],#允许跨域请求的HTTP头列表
)

FastAPI原文CORS(跨源资源共享)介绍:https://fastapi.tiangolo.com/tutorial/cors/