You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:06:10