reactjs - axios post请求错误,来自react的422(不可处理的实体)

标签 reactjs sqlalchemy axios fastapi

来自 FastAPI 和 sqlalchemy

@app.post("/users")
    def create_users(email: str, pwd: str, first_name: str, last_name: str, phone_number: str, city: str):
        user = UserTable()
        user.email = email
        user.pwd = pwd
        user.first_name = first_name
        user.last_name = last_name
        user.phone_number = phone_number
        user.city = city
    

        session.add(user)
        session.commit()
    
        return f"{email} created..."

响应 axios.post 请求

const addUserHandler =  () => {
        console.log(email, pwd, first_name, last_name, phone_number, city);
        axios
            .post('http://localhost:8000/users', {
                email: email,
                pwd: pwd,
                first_name: first_name,
                last_name: last_name,
                phone_number: phone_number,
                city: city,
            })
            .then((res) => console.log(res.data))
            .catch((error) => {
                console.log(error.response.data);
            });
        console.log(city);
    };

下面是错误代码

xhr.js:177 POST http://localhost:8000/users 422 (Unprocessable Entity)
App.js:37 
{detail: Array(6)}
detail: Array(6)
0: {loc: Array(2), msg: "field required", type: "value_error.missing"}
1: {loc: Array(2), msg: "field required", type: "value_error.missing"}
2: {loc: Array(2), msg: "field required", type: "value_error.missing"}
3: {loc: Array(2), msg: "field required", type: "value_error.missing"}
4: {loc: Array(2), msg: "field required", type: "value_error.missing"}
5: {loc: Array(2), msg: "field required", type: "value_error.missing"}
length: 6
__proto__: Array(0)
__proto__: Object

代码来自react&axios,我收到422错误并且无法发布。我确实检查了变量(useState)有一个每个字符串。但错误仍然显示“需要字段”和“value_error.missing”。我该如何解决这个问题?

感谢您的回复!

最佳答案

问题是你期待 "query params"在 url (fastapi) 中,而不是 json 正文中。

所以,

@app.post("/users")
    def create_users(email: str, pwd: str, first_name: str, last_name: str, phone_number: str, city: str):

期待类似的事情

/users?email=a&pwd=b&first_name=c...

尝试使用 Pydantic models ,这样 fastapi 将等待请求中的正文。

关于reactjs - axios post请求错误,来自react的422(不可处理的实体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68379986/

相关文章:

python - Flask-SQLAlchemy 过滤与父模型的多对多关系

python - 从 Python 中的模型在 Postgres DB 中创建表/生成模式

javascript - axios 获取请求响应,禁止 403 错误

vue.js - 如何使用 axios 填充 Vuetify DataTable

javascript - 为什么我们在React中创建类组件时要扩展React.Component?

javascript - 将 JSX 转换为 JSON 或 String,然后再转换回来

reactjs - React 将图像 src 作为对象返回

javascript - ReactJS 使用异步 setState 更新状态的最佳方法

python - SQLAlchemy 编写嵌套查询

node.js - Async + Axios - 速率控制