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

使用JavaScript的Fetch发送POST数据时遭遇422(无法处理实体)错误

解决POST请求422 Unprocessable Entity错误的方案

你的422错误核心原因是请求未正确声明数据格式,以下是具体解决步骤和排查点:

1. 添加上Content-Type请求头

你将数据转为JSON字符串后,没有告诉服务器这是JSON格式的请求体,而Swagger的/docs页面会自动添加这个必要头。修改你的fetch请求,在headers中加入:

'Content-Type': 'application/json'

修改后的完整函数示例:

function submitProject() {
    const formData = JSON.stringify(projectFormData);
    
    fetch('http://localhost:8000/projects/', {
        method: 'POST',
        headers: {
            Authorization: data.soundhub_api_key,
            'Content-Type': 'application/json'
        },
        body: formData
    }).then((response) => {
        response
            .json()
            .then((responseData) => {
                const r = { status: response.status, body: responseData };
                if (r.status == 200) {
                    console.log('success');
                    if (errorList.length > 0) {
                        errorList = [];
                    }
                } else {
                    console.log('error');
                    console.log(r.body.detail);
                    errorList = r.body.detail;
                }
            })
            .catch((error) => {
                console.log('error occurred');
                console.error(error);
                return [];
            });
    });
}

2. 排查其他可能问题

  • 确认字段类型匹配:确保所有数字类型字段(如taxonomy_id、sensor_layout_id)是数字而非字符串,你的当前代码中是正确的,但要避免后续修改时误转为字符串。
  • 对比请求头差异:用浏览器开发者工具(F12→网络面板)查看/docs页面提交请求时的完整请求头,对比你的fetch请求,确认是否有其他必要头缺失(比如部分API要求Accept: application/json,可一并添加到headers中)。
  • 不要使用FormData:你的API接受JSON格式请求体,FormData是表单编码格式,与服务器期望的格式不匹配,这也是你转FormData后依然失败的原因。

内容的提问来源于stack exchange,提问作者user2030942

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:10:27