Я проверил документацию 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=["*"],
)
app = FastAPI()
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.
Как решить эту проблему?
EDIT: сервер выдает эту ошибку:
Код: Выделить всё
"OPTIONS /posts HTTP/1.1" 405 Method Not Allowed
Подробнее здесь: https://stackoverflow.com/questions/792 ... middleware