-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.

1 Answers1

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:
    ...
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • can you check my code again? sorry for bothering – Jaewon Choi Sep 16 '22 at 09:13
  • 1
    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. – MatsLindh Sep 16 '22 at 09:27