Fetch请求返回422错误:'value is not a valid dict'求助
解决POST请求返回422错误的问题
422(Unprocessable Entity)错误说明API无法处理你的请求,虽然请求体内容和Insomnia一致,但核心问题是fetch请求缺少Content-Type请求头——Insomnia会自动为JSON请求体添加Content-Type: application/json,但原生fetch默认不会添加这个头,导致API无法识别请求体的格式。
修复步骤:
- 在
requestOptions中添加headers配置,明确指定请求体类型为JSON - 同时确认
startDate和endDate的格式与Insomnia中完全一致(比如是否为YYYY-MM-DD格式的字符串)
修改后的代码:
const[stopinfo, setStopInfo] = useState([]); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' // 新增请求头配置 }, body: JSON.stringify({ 'min_date': startDate, 'max_date': endDate, 'min_time': '00:00:00', 'max_time': '23:00:00', 'bus_ids': [2,3,4], 'route_ids': [1,2,3] }) }; const fetchStopData = async () => { try { const response = await fetch("https://mywebsite.com/api/data/stopinfo", requestOptions); if (!response.ok) { // 打印错误详情方便排查 const errorData = await response.json(); console.error('API错误详情:', errorData); throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); setStopInfo(data); } catch (error) { console.error('请求出错:', error); } }; useEffect(() => { fetchStopData(); }, []);
额外排查点:
- 检查
startDate和endDate是否为API要求的格式,比如是否是字符串类型,有没有出现日期格式错误(如MM/DD/YYYY而非YYYY-MM-DD) - 打开浏览器开发者工具的Network面板,对比当前请求的Headers、Body与Insomnia请求的差异,确认所有参数完全一致
内容的提问来源于stack exchange,提问作者Jack A
相关产品推荐
相关产品推荐

