-2

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.

3
  • Your request body has translateTo, but your backend is expecting translate. That is the problem. async def translate(text: str, translate: str) -> str: probably should be async def translate(text: str, translateTo: str) -> str: Commented Sep 16, 2022 at 8:16
  • data should be a JSON string? body: JSON.stringify(data)? Commented Sep 16, 2022 at 8:20
  • This is not working too :( Commented Sep 16, 2022 at 9:13

1 Answer 1

2

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:
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

can you check my code again? sorry for bothering
That error is usually caused by a server side error - check the log in your FastAPI application and see what it complains about. If you check your browser's developer tools and the Network tab you'll probably see that the response is an 500 error instead of the expected response.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.