编辑后
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)我正确地更改了变量的名称,并将后端参数旁边的主体相加,然后系统显示了这个错误。
从源'http://localhost:8000/translate‘获取'http://localhost:3000’的访问已被CORS策略阻止:请求的资源上没有“访问控制-允许-原产地”标题。如果不透明响应满足您的需要,请将请求的模式设置为“no- CORS”,以获取禁用CORS的资源。
虽然我接受所有的起源,我真的不知道为什么这个错误造成。
发布于 2022-09-16 08:15:40
您必须告诉FastAPI您的text和translate字段是JSON字段(您需要在请求中使用正确的名称- translate而不是translateTo):
async def translate(text: str = Body(), translate: str = Body()) -> str:您还可以创建一个Pydantic模型来描述您期望的东西--这将自动地期望它是一个JSON主体:
from pydantic import BaseModel
class TranslationRequest(BaseModel):
text: str
translate: str
@app.post("/translate")
async def translate(translate_details: TranslationRequest) -> str:
...https://stackoverflow.com/questions/73741815
复制相似问题