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

React调用Flask REST API时报Unhandled Rejection: Failed to fetch错误如何解决

问题描述

我正在开发一款应用,后端用Flask写了REST API,可接收两个字符串参数,返回浮点型预测值。当前我正尝试将该接口对接至React应用,以实现预测结果在网页端的展示。

以下是React应用中调用REST API获取预测结果的代码:

function App() {
  useEffect(() => {
    fetch(
      "https://flask-api-test1.herokuapp.com/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O"
    )
      .then((resp) => {
        if (resp.status == 200) {
          return resp.json();
        }
      })
      .then((data) => {
        console.log(data);
      });
  }, []);

上述fetch请求路径/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O中,solute=CC(C)(C)Br和solvent=CC(C)(C)O是Flask REST API生成预测结果所需的入参。
我运行上述代码尝试在控制台输出返回结果时,出现了跨域报错。

解决方案

这个报错是浏览器同源策略导致的跨域资源共享(CORS)限制,你只需要在Flask后端配置允许跨域访问即可,具体操作如下:

  • 第一步:安装Flask-CORS扩展
    pip install flask-cors
  • 第二步:在Flask入口文件中配置CORS
    from flask import Flask, request
    from flask_cors import CORS
    
    app = Flask(__name__)
    # 开发阶段可以直接允许所有来源,生产环境建议替换为你的React应用实际域名
    CORS(app)
    
    # 原有的predict接口逻辑保持不变
    @app.route('/predict', methods=['GET'])
    def predict():
        solute = request.args.get('solute')
        solvent = request.args.get('solvent')
        # 你的预测逻辑
        return {"result": 预测值}
    

如果需要更严格的安全控制,仅允许你的React应用访问接口,可以将配置修改为:
CORS(app, origins=["http://localhost:3000"])
把里面的地址替换为你React应用实际的访问地址即可。

另外你可以优化前端的fetch代码,补充异常捕获逻辑,方便后续排查问题:

function App() {
  useEffect(() => {
    fetch("https://flask-api-test1.herokuapp.com/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O")
      .then((resp) => {
        if (resp.ok) {
          return resp.json();
        }
        throw new Error(`请求失败,状态码:${resp.status}`);
      })
      .then((data) => {
        console.log("预测结果:", data);
      })
      .catch((err) => {
        console.error("接口调用出错:", err);
      });
  }, []);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:09:01