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

Python/Flask/JS返回JSON化数据时出错:SyntaxError: Unexpected end of input

问题原因与解决方案

核心问题

你前端代码里的{mode: 'no-cors'}是导致错误的关键。这种模式下,浏览器会将后端返回的响应标记为不透明响应(opaque response),完全禁止JavaScript读取响应内容,所以调用res.json()时会因为没有可解析的JSON数据报SyntaxError: Unexpected end of input。

解决步骤

1. 后端Flask配置跨域支持

首先安装跨域扩展:

pip install flask-cors

然后在Flask代码中启用CORS:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
# 允许所有前端域名访问,若要限制可替换为特定域名,比如"http://localhost:3000"
CORS(app)

# 你的/deepface路由
@app.route('/deepface')
def deepface():
    # 此处保留你的detection_data等业务逻辑
    responseAPI = {
        "data": detection_data["Race"],
        "gender": detection_data["Gender"],
        "age": detection_data["Age"],
        "job": most_probable_job,
        "jobAlternatives": Job_alternatives,
        "raceAlternatives": Race_alternatives,
    }   
    return jsonify(responseAPI)

2. 修改前端fetch代码,移除no-cors模式

window.onload = () => {
    console.log("hello");
    fetch('http://localhost:5000/deepface')
        .then(res => {
            // 先检查响应状态是否正常
            if (!res.ok) {
                throw new Error('请求失败,状态码:' + res.status);
            }
            return res.json();
        })
        .then(r => {
            console.log(r);
            // 这里可以开始处理并渲染JSON数据
        })
        .catch(err => {
            console.error('请求出错:', err);
        });
}

额外说明

  • 不要使用no-cors模式来解决跨域问题,这是一种限制级的模式,仅适用于不需要读取响应内容的场景。正确的做法是在后端配置CORS,允许前端域名的跨域请求。
  • 确保前后端的端口、域名匹配,比如前端运行在http://localhost:3000,后端在http://localhost:5000,CORS配置要对应允许这个前端域名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:11:00