简体   繁体   English

我怎样才能获取到 fastapi

[英]how can i fetch to fastapi

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我正确更改了变量的名称并在后端参数旁边添加了 Body 然后现在系统显示此错误

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. CORS 策略已阻止从源“http://localhost:8000/translate”获取“http://localhost:8000/translate”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”header . If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

Though I accept all origin, I really don't know why this error caused.虽然我接受所有来源,但我真的不知道为什么会导致这个错误。

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 ):您必须告诉 FastAPI 您的texttranslate字段是 JSON 正文字段(并且您需要在请求中使用正确的名称 - translate而不是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:您还可以创建一个 Pydantic model 来描述您的期望 - 这将自动将其预期为 JSON 主体:

from pydantic import BaseModel


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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM