Axios和FastApi的一些坑

写在

刚开始接触 FastApi 想做个小项目玩玩,前端用的React在用axios发送post请求时出现422错误??,422错误是指发送的post请求的字段和后台的接收字段不对应导致的

@router.post('/paper/like')
def like(pid: int):
    res = paper.like(pid)
    if res >= 1:
        return {'message': 'success'}
    else:
        return {'message': 'failed'}

这是会报错的后端代码,看上去很正常对吧,就是一个字段pid呀,摸索了半天才发现原来是FastApi的验证所导致的,使用Pydantic模型后可以正常接收请求!

class LikePaper(BaseModel):
    pid: int

@router.post('/paper/like')
def like(item: LikePaper):
    res = paper.like(item)
    if res >= 1:
        return {'message': 'success'}
    else:
        return {'message': 'failed'}

这样使用Pydantic模型修改代码后就可以正常运行啦~

axios发送请求失败
fastapi自带的docs可以发送


评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注