ReactJS与Flask后端CORS跨域问题排查求助
解决Flask + React CORS拦截及415状态码问题
先处理415状态码(媒体类型不支持)
415通常是后端未正确识别前端请求格式,或前端未设置正确请求头导致的:
- 确保Flask启用JSON解析:在
main.py中添加解析逻辑,避免无法识别JSON请求from flask import Flask, request app = Flask(__name__) @app.before_request def parse_json_request(): if request.is_json: # 自动解析JSON请求体,方便后续直接使用request.get_json() request.parsed_data = request.get_json() - 检查前端
API.js的请求配置,必须显式设置Content-Type为application/json,同时如果需要携带Cookie,要加上credentials: 'include':const callApi = async () => { try { const response = await fetch('http://localhost:5000/api/your-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + yourAuthToken // 如有认证需携带 }, credentials: 'include', body: JSON.stringify({ key: 'value' }) }); const data = await response.json(); return data; } catch (err) { console.error(err); } };
修复CORS的Access-Control-Allow-Credentials问题
报错提示预请求的该头为空,核心是Flask-CORS配置未正确开启凭证支持,且带凭证的请求不能用*作为允许的源:
- 全局配置Flask-CORS(在
__init__.py或main.py中):from flask_cors import CORS # 指定前端实际域名,比如React默认的localhost:3000,生产环境替换为真实域名 CORS(app, origins=['http://localhost:3000'], supports_credentials=True) - 禁止手动编写OPTIONS路由:如果
auth.py中有自定义OPTIONS请求处理逻辑,直接删除,Flask-CORS会自动处理预请求,手动编写会覆盖默认的CORS头配置 - 若必须自定义OPTIONS处理(比如特殊权限校验),需手动添加完整CORS头:
from flask import make_response @app.route('/api/auth', methods=['OPTIONS']) def handle_auth_options(): response = make_response() response.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization' response.headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS' response.headers['Access-Control-Allow-Credentials'] = 'true' return response
验证配置有效性
打开浏览器开发者工具的「网络」标签,查看OPTIONS预请求的响应头,确认以下内容存在:
Access-Control-Allow-Origin:与前端域名完全一致(不能是*)Access-Control-Allow-Credentials: true
同时检查实际业务请求的响应头,也需包含上述两项。
常见避坑点
- 前端必须设置
credentials: 'include',否则后端supports_credentials=True不会生效 - 若使用Flask蓝图(Blueprint),需给蓝图单独配置CORS,或全局配置时包含蓝图路由:
from flask import Blueprint from flask_cors import CORS auth_bp = Blueprint('auth', __name__) CORS(auth_bp, origins=['http://localhost:3000'], supports_credentials=True) - 检查后端是否有其他中间件(如身份验证中间件)在CORS之前拦截请求,导致CORS头未被正确添加
内容的提问来源于stack exchange,提问作者LordAssalt
相关产品推荐
相关产品推荐

