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

从JQuery AJAX切换到Fetch API为何触发422错误?

FastAPI从jQuery AJAX迁移到Fetch API遇422错误的解决方法

问题描述

尝试将小型FastAPI Web应用从jQuery AJAX迁移到Fetch API时遇到问题:原AJAX调用能正常向服务器发送JSON数据并被后端处理,但Fetch API实现返回422错误,响应消息为"value is not a valid dict"。

原jQuery AJAX代码:

static run_task_one(E1, E2, E3, n1, n2, success, error) {
    $.ajax({
        url: "/run/task/one",
        type: "POST",
        data: JSON.stringify({
            E1: E1,
            E2: E2,
            E3: E3,
            n1: n1,
            n2: n2,
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: success,
        error: error,
    });
}

Fetch API实现代码:

static run_task_one(E1, E2, E3, n1, n2, success, error) {
    fetch("/run/task/one", {
        method: "POST",
        body: JSON.stringify({
            E1: E1,
            E2: E2,
            E3: E3,
            n1: n1,
            n2: n2,
        }),
        headers: {
          contentType: "application/json; charset=utf-8",
        },
    })
    .then((response) => response.json())
}

已确认两个请求的payload完全一致:

{"E1":"0.92","E2":"1.1","E3":"1.43","n1":"0.0025","n2":"0.0005"}

解决方法

问题出在Fetch API的请求头设置上:HTTP请求头的键名需要严格遵循标准格式,你写的contentType是驼峰小写,正确的写法应该是**Content-Type**(首字母大写,中间连字符分隔)。

jQuery会自动规范请求头格式,但Fetch API不会做这个处理,导致服务器无法识别请求体是JSON格式,FastAPI的Pydantic模型也就无法解析请求内容,最终返回422验证错误。

修正后的Fetch代码:

static run_task_one(E1, E2, E3, n1, n2, success, error) {
    fetch("/run/task/one", {
        method: "POST",
        body: JSON.stringify({
            E1: E1,
            E2: E2,
            E3: E3,
            n1: n1,
            n2: n2,
        }),
        headers: {
          "Content-Type": "application/json; charset=utf-8", // 修正请求头键名
        },
    })
    .then((response) => {
        if (!response.ok) {
            throw new Error(response.statusText); // 处理HTTP错误状态,触发error回调
        }
        return response.json();
    })
    .then(success)
    .catch(error);
}

额外补充:

  • Fetch API默认不会将HTTP错误状态码(如422)视为Promise异常,所以需要手动判断response.ok,确保错误场景能触发传入的error回调。
  • 问题和Pydantic本身无关,只是服务器无法识别请求体格式,导致Pydantic无法完成解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:41:17