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
相关产品推荐
相关产品推荐

