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

使用Fetch API向Flask服务器发送JSON对象时出现400错误

Flask POST JSON 400错误排查与解决

我参考线上文章及Flask官方文档尝试向服务器发送JSON数据,但持续出现400错误,试过多种方法都无效。已知Flask在未接收到格式正确的JSON数据,或请求未指定Content-Type为application/json时会触发该错误。

Flask视图函数代码

@main.route('/test', methods=['GET','POST'])
def test():

    if request.method == 'POST':
        print(request.method)
        print(request.headers.get('Content-Type'))
        print(request.is_json)
# 取消注释后会触发400错误
        #print(request.json)

    return render_template('test.html')

前端test.html脚本代码

<script>
    let data = {"data": "Hello World!"}

    document.querySelector('#main').addEventListener('click', function () {
        fetch('/test', {
            method: "POST",
            body: JSON.stringify(data),
            headers: {"Content-Type": "application/json"},
            credentials: "same-origin"
        })
        .then(response => console.log(response.json))
    })
</script>

终端输出结果

每次点击按钮发送POST请求时,终端输出如下:

POST
text/plain;charset=UTF-8
False

解决思路

  • 改用Headers对象构造请求头:部分场景下直接通过对象设置headers会被浏览器自动覆盖,尝试显式构建请求头:
    const headers = new Headers();
    headers.set('Content-Type', 'application/json');
    
    fetch('/test', {
        method: "POST",
        body: JSON.stringify(data),
        headers: headers,
        credentials: "same-origin"
    })
    
  • 排查请求头被篡改的可能:检查页面是否存在全局fetch拦截器,或浏览器插件(如调试工具、广告拦截器)修改了请求头,可尝试在隐身模式下测试。
  • 用request.get_json()替代request.json调试:request.get_json()支持silent=True参数,不会因请求头问题直接抛出400,便于排查数据解析情况:
    if request.method == 'POST':
        print(request.method)
        print(request.headers.get('Content-Type'))
        print(request.is_json)
        # 静默解析,不会触发400
        data = request.get_json(silent=True)
        print(data)
    
  • 检查Flask全局中间件:确认是否有第三方扩展或自定义中间件修改了请求的Content-Type,排查并临时禁用相关中间件测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:06:45