提取Fastapi邮政请求
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的答案。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用户
是用户输入的任何字符串。然后,您将这些绳子放入体内,完全原始,并声称它是JSON。
用户似乎不太可能在电子邮件字段中输入JSON。
如果您告诉服务器您要发送JSON,则需要实际发送JSON。
虽然我对Fastapi并不熟悉,但看起来像是预期的JSON文本:
因此您需要构造:
user
is whatever string the user typed in.And you are putting that string into the body, completely raw, and claiming that it is JSON.
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:
So you need to construct that:
在服务器上尝试一下。
您的代码没有启用CORS。如果您使用的是跨域请求,则需要启用它。
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.