前端页面通过apisix网关访问后端的Fastapi的跨域问题CORS
·
问题出现:
在使用Vue3和Fastapi做前后端分离项目时,前端页面调用apisix网关再路由到后台fastapi的restfull接口 console报错:
Access to XMLHttpRequest at 'http://192.168.110.45:9080/retrieval_test_data_1030' from origin 'http://192.168.140.2:5100' 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)apisix的路由HTTP的方法需要添加支持OPTION选项

2)FastApi后台的服务需要添加CORSMiddleware
app = FastAPI()
#设置允许跨域
origins = [
"http://192.168.110.45",
"http://192.168.140.2",
"http://192.168.110.45:9080",
"http://192.168.140.2:5100",
"http://192.168.110.45:5100",
]
# 后台api允许跨域
app.add_middleware(
CORSMiddleware,
allow_origins=origins , #这里可以填写["*"],表示允许任意ip
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/')
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app="gui:app", port=5100, host="0.0.0.0", workers=3)
3)再次访问后正常。
更多推荐


所有评论(0)