提取Fastapi邮政请求

发布于 2025-02-05 09:09:27 字数 1525 浏览 1 评论 0 原文

JavaScript代码:

 const submitHandler = async (e) => {
 
     const user = document.getElementById("email").value;

     await fetch('https://clownfish-app-fqu4k.ondigitalocean.app/meadow', {
         method: "POST",
         headers: "content-type": "application/json",
         body: user,
      })

   }

Python:

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class User(BaseModel):
    email: str


@app.post("/meadow")
def password_validation(user: User):
    return {
        "status": "success",
        "data": user
    }

以上在Postman中效果很好,但是在Chrome中给出以下错误:

任何帮助将不胜感激。

我已经更新了代码以包括以下建议。没有快乐。该请求导致422错误 - “无法处理的实体”。我是否应该如答案? 我还尝试将获取标头设置为“接受”。

更新 请求是导致

{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}

一个

我的 新手错误 - 发送数据之前,我没有将数据串起。请参阅下面的 @Quentin的答案。

Javascript code:

 const submitHandler = async (e) => {
 
     const user = document.getElementById("email").value;

     await fetch('https://clownfish-app-fqu4k.ondigitalocean.app/meadow', {
         method: "POST",
         headers: "content-type": "application/json",
         body: user,
      })

   }

Python:

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class User(BaseModel):
    email: str


@app.post("/meadow")
def password_validation(user: User):
    return {
        "status": "success",
        "data": user
    }

The above works fine in Postman, but in Chrome gives the following error:
enter image description here

Any help would be appreciated.

I've updated the code to include the suggestions below. No joy. The request results in a 422 error - an "Unprocessable Entity". Should I be using the FormData class as mentioned in this answer?
I've also tried setting the fetch headers to 'accept'.

UPDATE
My request is resulting in a

{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}

so I'm not sending the data in the way Pydantic is expecting it

UPDATE 2
Novice mistake - I wasn't stringifying the data before sending it. See @Quentin's answer below.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅暮の光 2025-02-12 09:09:27

用户是用户输入的任何字符串。

  const user = document.getElementById(“ email”)。value;
 

然后,您将这些绳子放入体内,完全原始,并声称它是JSON。

 标题:“ content-type”:“ application/json”,
    身体:用户,
 

用户似乎不太可能在电子邮件字段中输入J​​SON。

如果您告诉服务器您要发送JSON,则需要实际发送JSON。

虽然我对Fastapi并不熟悉,但看起来像是预期的JSON文本:

{ "email": "some value" }

因此您需要构造:

body: JSON.stringify({ email: user })

user is whatever string the user typed in.

const user = document.getElementById("email").value;

And you are putting that string into the body, completely raw, and claiming that it is JSON.

    headers: "content-type": "application/json",
    body: user,

It seems unlikely that the user is typing JSON into the email field.

If you tell the server you are sending JSON, then you need to actually send JSON.

While I'm not remotely familiar with FastAPI, it looks like the JSON text that is expected is:

{ "email": "some value" }

So you need to construct that:

body: JSON.stringify({ email: user })
雨巷深深 2025-02-12 09:09:27

在服务器上尝试一下。

您的代码没有启用CORS。如果您使用的是跨域请求,则需要启用它。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class User(BaseModel):
    email: str


@app.post("/meadow")
def password_validation(user: User):
    return {
        "status": "success",
        "data": user
    }

Try this on your server.

Your code doesn't have CORS enabled. You need to enable it, if you are using a cross domain request.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class User(BaseModel):
    email: str


@app.post("/meadow")
def password_validation(user: User):
    return {
        "status": "success",
        "data": user
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文