使用FastAPI开发接口时,跨域调用报错如下:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/API/ADMIN/ADDUSER' 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.
解决办法:
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原文介绍:https://fastapi.tiangolo.com/tutorial/cors/