FastAPI配置CORSMiddleware后仍存在CORS跨域问题及后续405、422错误的排查与解决咨询
FastAPI配置CORSMiddleware后仍存在CORS跨域问题及后续405、422错误的排查与解决咨询
我在本地localhost:3000的前端调用FastAPI后端(localhost:4000)时遇到了CORS跨域问题,已经参照FastAPI文档添加了相关代码来处理,但问题依然存在,一直收到跨域错误提示。
最初的后端代码:
import httpx from fastapi import FastAPI from pydantic import BaseModel from starlette.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost:3000" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) msgs=dict() class Body(BaseModel): title: str class Msg(BaseModel): type: str content: dict @app.post("/posts/") async def posts(body: Body): number= len(msgs)+1 title = body msgs[number]= { "type": "PostCreated", "data": { "id": number, "title": title.title } } api_url = "http://localhost:4005/events" async with httpx.AsyncClient() as client: response = await client.post(api_url, json={ "type": "PostCreated", "data": { number, title } }) return msgs @app.post("/events/") async def event_monitoring(msg: Msg) : print(msg.type) @app.get("/posts/") async def root(): return msgs
收到的跨域错误提示:
Access to XMLHttpRequest at 'http://localhost:4000/posts/' from origin 'http://localhost:3000' 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:服务器日志返回错误
"OPTIONS /posts HTTP/1.1" 405 Method Not Allowed
明明已经设置了allow_methods=["*"]允许所有请求方法,还是出现了这个405错误。
编辑2:调整代码后CORS问题解决,但出现422错误
修改后的代码如下(主要修正了事件推送的JSON格式和API路径):
import httpx from fastapi import FastAPI from pydantic import BaseModel from starlette.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost:3000" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) msgs=dict() class Body(BaseModel): title: str class Msg(BaseModel): type: str content: dict @app.post("/posts/") async def posts(body: Body): number= len(msgs)+1 title = body msgs[number]= { "type": "PostCreated", "data": { "id": number, "title": title.title } } api_url = "http://localhost:4005/events/" async with httpx.AsyncClient() as client: response = await client.post(api_url, json={ "type": "PostCreated", "data": { "id": number, "title": title.title } }) return msgs @app.post("/events/") async def event_monitoring(msg: Msg) : print(msg.type) @app.get("/posts/") async def root(): return msgs
编辑3:最终解决422错误
发现问题出在Msg类的定义上,原来的字段名和实际接收的JSON字段不匹配,修正后问题彻底解决:
class Msg(BaseModel): type: str data: dict
备注:内容来源于stack exchange,提问作者EagleStar
相关产品推荐
相关产品推荐

