FastAPI接口Swagger/Postman正常,$.ajax POST返回422错误求助
问题原因及修复方案
核心问题
你在前端错误地将多选select的选中值用JSON.stringify()转成了字符串,但FastAPI的FilterModel期望接收数组类型(list[str]),后端收到字符串而非数组时,会触发422验证错误。
修复后的前端代码
直接使用$('#state_abbrev').val()返回的数组(多选select的val()本身就会返回选中值的数组),不需要单独对数组做字符串化,只需将整个请求数据对象转为JSON字符串即可:
<script> const form = document.getElementById('map-filter-form'); $(document).ready(function(){ form.addEventListener('submit', (e) => { e.preventDefault(); // 直接获取选中值数组,无选中项时返回空数组避免null const states = $('#state_abbrev').val() || []; const card_types = $('#card_type').val() || []; const data = {"state_abbrev": states, "card_type": card_types}; $.ajax({ url: "http://localhost:8000/mapview/filter", type: "post", // 对整个数据对象做JSON字符串化 data: JSON.stringify(data), contentType: "application/json", success: function(rslts) {console.log(rslts)} }); }); }); </script>
后端代码额外修复
你的后端代码存在两处逻辑问题,会导致运行报错:
- 变量名错误:
if biz_type:应该改为if card_type: - 未初始化
cards变量:如果state_abbrev为空,后续调用cards.filter()会报错
修复后的后端代码:
class FilterModel(BaseModel): state_abbrev: list[str] = [] card_type: list[str]= [] def get_db(): try: db = SessionLocal() yield db finally: db.close() @router.post('/filter') async def filter_cards(filterModel: FilterModel, db: Session=Depends(get_db)): state_abbrev = filterModel.state_abbrev card_type = filterModel.card_type # 初始化查询对象 cards = db.query(models.Cards) if state_abbrev: cards = cards.filter(models.Cards.state_abbrev.in_(state_abbrev)) # 修正变量名错误 if card_type: cards = cards.filter(models.Cards.card_type.in_(card_type)) cards = cards.all() return {"cards":cards}
内容的提问来源于stack exchange,提问作者Bill Tate
相关产品推荐
相关产品推荐

