【问题标题】:axios post request error with 422 (Unprocessable Entity) from react来自反应的 422(不可处理实体)的 axios 发布请求错误
【发布时间】:2021-07-14 14:29:41
【问题描述】:

来自 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”。我该如何解决这个问题?

感谢您的回复!

【问题讨论】:

    标签: reactjs sqlalchemy axios fastapi


    【解决方案1】:

    问题是您在 url (fastapi) 中期待 "query params",而不是 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 将等待请求中的正文。

    【讨论】:

    • 非常感谢!所以你的意思是在 fastapi 中我必须使用 pydantic model(json) 而不是查询参数,例如 (email : str ..) ?感谢您的反馈,我会深入了解更多!
    • 是的,您应该在尝试创建/更新资源(POST、PUT、PATCH)时使用模型
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多