Axios和FastApi的一些坑_

@时雨#日记2022/4/143 分钟

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

Text
@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模型后可以正常接收请求!

Text
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可以发送

$ls -lt ./articles
├─
[prev]上一篇Python 的 async@2022/4/11
└─
[next]下一篇React 100%屏幕高度@2022/4/14
────────────────────────
$cat ./comments

评论 (0)

暂无评论,来抢沙发吧

EOF_