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

React前端POST JSON至Flask后端报Content-Type错误求助

解决React POST JSON到Flask时的Content-Type错误

核心问题分析

你遇到的错误本质是跨域请求未被正确处理或请求数据/时机存在异常,导致Flask端无法识别请求的Content-Type为application/json。以下是针对性的修复方案:


方案1:Flask端添加CORS支持并优化请求处理

跨域场景下(React默认3000端口,Flask默认5000端口),浏览器会先发OPTIONS预检请求,若Flask未处理CORS,会导致实际请求的Content-Type头被拦截。同时优化请求解析逻辑,增强健壮性:

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
# 允许React所在域名的跨域请求,可指定具体origin而非通配符
CORS(app, origins=["http://localhost:3000"])

@app.route("/moviesSent", methods=['POST'])  # 仅保留POST方法,符合接口用途
def get_movies_recommended():
    # 显式检查请求是否为JSON格式
    if not request.is_json:
        return jsonify({"error": "请求必须为JSON格式"}), 400
    
    # 使用get_json()解析请求,比直接request.json更可靠
    movies = request.get_json()
    try:
        data = movies["data"]
        # 用jsonify返回响应,自动设置正确的Content-Type头
        return jsonify({"movies": data})
    except KeyError:
        return jsonify({"error": "请求缺少'data'字段"}), 400

安装依赖

执行命令安装flask-cors:

pip install flask-cors

方案2:React端优化请求逻辑与副作用时机

修复useEffect依赖问题,增加数据格式校验,避免无效请求:

// 初始化时兜底,防止localStorage返回null导致JSON.parse报错
const obj = JSON.parse(localStorage.getItem('selectedMovies')) || { data: [] };

const sendMovieId = async () => {
    try{
        // 先校验数据格式合法性
        if (!obj.data || !Array.isArray(obj.data)) {
            console.error('数据格式错误:缺少合法的data数组');
            return;
        }

        const res = await fetch('http://127.0.0.1:5000/moviesSent', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(obj),
        });

        // 用res.ok判断请求成功,覆盖200-299状态码
        if (res.ok) {
            localStorage.setItem('moviesSelectedStatus', 'true');
            navigate('/secondPage');
        } else {
            const errorInfo = await res.json();
            console.error('服务器错误:', errorInfo);
        }
    }catch(e){
        console.error('请求发送失败:', e);
    }
}

// 添加依赖数组,仅当obj或navigate变化时执行副作用
useEffect(() => {
    if (obj.data.length > 0) {
        sendMovieId();
    } else {
        console.log('无有效数据可发送');
    }

    if (localStorage.getItem('moviesSelectedStatus')) {
        navigate('/secondPage');
    }
}, [obj, navigate]);

验证步骤

  1. 打开浏览器开发者工具的Network标签,查看POST请求的Headers,确认Content-Type确实为application/json。
  2. 检查Request Payload,确认发送的JSON数据格式正确。
  3. 确保Flask和React服务都正常启动,端口配置无误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:20:25