【问题标题】:Python FastApi error 422 (Unprocessable Entity)Python FastApi 错误 422(无法处理的实体)
【发布时间】:2020-11-16 16:40:07
【问题描述】:

当我使用 POST 请求从运行在端口 5500 上的 JS 脚本使用 XMLHttpRequest 将表单数据发送到我的后端(在端口 8000 上运行的 FastAPI 应用程序)时,我总是遇到此错误 Unprocessable Entity。 这是服务器端:

origins = ["https://localhost:5500"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.post("/test")
def test(username: str = Form(...)):
    print(f"########### Received {username} #############")

这是客户端代码:

async function sendData() {
    formData = new FormData();
    formData.append('username', 'Kareem');
    const response = await fetch('http://localhost:8000/test', {
        method: 'POST',
        data: formData
    })
}

【问题讨论】:

  • 响应正文中的错误是什么?
  • 应该是 https 还是 http,因为它是 localhost?
  • @MahirMahbub 我都试过了
  • 我在我的服务器上试过你的代码。它工作正常。我认为他们的 ia 后端配置错误或前端有问题。有没有在 swgger 或者其他工具中测试过这个 api?
  • @Mause 响应 {type: "cors", url: "localhost:8000/test", 重定向: false, status: 422, ok: false, ...} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 422 statusText: "Unprocessable Entity" type: "cors" url: "localhost:8000/test" proto: Response

标签: javascript python python-3.x backend fastapi


【解决方案1】:

您好,我遇到了同样的问题。我使用了 URLSearchParams。

这是我的代码

let urlencoded = new URLSearchParams();
urlencoded.append("username", username);
urlencoded.append("password", password);


try {
    setLoading(true);
    const response =  await fetch("http://127.0.0.1:5000/login", {
        method: 'POST',
        headers: {
             "Content-Type" : "application/x-www-form-urlencoded"
        },
        body: urlencoded,
        redirect: 'follow'

    })

【讨论】:

  • 你能解释一下为什么吗?代码 sn-p 抛出错误,因此很难在上下文中理解。
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 2021-03-15
  • 2018-03-01
  • 1970-01-01
相关资源
最近更新 更多