how can i fetch to fastapi

Viewed 47

After edit

const data = {
      text: text,
      translateTo: translateTo,
    };

    await fetch("http://localhost:8000/translate", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
backend
origins = [
    "*"
]


app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

@app.post("/translate")
async def translate(text: str = Body(), translateTo: str = Body()) -> str:
    return apiTranslateLang(text, translateTo)

I changed the name of the variable correctly and added up the Body next to the backend parameter then now the system show that this error

Access to fetch at 'http://localhost:8000/translate' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Though I accept all origin, I really don't know why this error caused.

1 Answers

You'll have to tell FastAPI that your text and translate fields are JSON body fields (and you need to use the correct name in your request - translate not translateTo):

async def translate(text: str = Body(), translate: str = Body()) -> str:

You can also create a Pydantic model that describes what you expect - this will automagically expected it as a JSON body:

from pydantic import BaseModel


class TranslationRequest(BaseModel):
    text: str
    translate: str


@app.post("/translate")
async def translate(translate_details: TranslationRequest) -> str:
    ...
Related