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

Flask+React无法解析JSON报‘unexpected character’错误排查与解决

Flask后端与React前端交互的问题排查及解决

一、使用的代码及配置

Flask后端代码

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)


@app.route("/")
def home():
    return {"name": "John", "age": 30}


if __name__ == "__main__":
    app.run(debug=True)

React前端代码

function App() {

  const [data, setData] = useState([{}])

    useEffect(() => {
        fetch("http://localhost:5000/").then(
            res => res.json()
        ).then(
            data => {
                setData(data)
                console.log(data)
            }
        )
    }, [])

  return (
    <div className="App">
    </div>
  );
}

额外配置

在React项目的package.json中添加了代理设置:

"proxy": "http://localhost:5000/"

二、遇到的问题及排查过程

初始错误

前端始终收到JSON解析失败的错误:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

后续CORS错误

添加CORS配置、调整fetch地址和proxy配置后,出现跨域相关错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/. (Reason: CORS request did not succeed). Status code: (null) Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

最终定位原因

发现上述CORS错误是因为fetch请求误使用了https协议,修正为http后问题解决,正确的fetch代码片段如下:

useEffect(() => {
    fetch("http://localhost:5000/")
    // 后续响应处理逻辑
})

三、问题根源及解决方案

初始JSON解析错误的原因

  1. 请求未获取到有效JSON:如果Flask服务未正常启动,或者请求地址/协议错误,前端拿到的不是合法的JSON字符串,就会触发解析失败。
  2. 代理配置冲突:同时使用package.json的proxy和fetch全地址,可能导致请求路径异常,返回非JSON内容。

对应解决方法

  1. 先验证后端服务:直接在浏览器访问http://localhost:5000/,确认页面显示{"name": "John", "age": 30},确保服务正常运行。
  2. 统一请求配置:要么保留proxy,fetch使用相对路径fetch("/");要么去掉proxy,直接用全地址http://localhost:5000/,同时确保协议为http。

CORS错误的核心原因及解决

错误根源是请求协议不匹配(比如前端页面用https加载,但请求后端http地址,浏览器会拦截跨域请求)。解决方法就是保证fetch的协议与后端服务一致,Flask默认启动http服务,所以fetch必须写http://localhost:5000/,不能用https。另外,Flask已配置CORS(app),只要地址正确,跨域问题就能解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:12:04