React对接Flask后端遭遇CORS跨域问题,求排查与解决方案
错误信息
Access to XMLHttpRequest at 'http://localhost:5000/api/auth/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
问题根源分析
路由路径重复定义:
Flask蓝图auth_bp注册时指定了url_prefix='/api/auth',但auth.py中路由却写成@auth_bp.route('/api/auth/register'),导致实际接口路径变为/api/auth/api/auth/register,与前端请求的/api/auth/register不匹配。Flask无法找到对应路由,返回404响应,自然不会携带CORS头,引发错误。未配置凭证支持:
前端axios设置了withCredentials: true,但后端CORS配置未开启supports_credentials=True。根据CORS规则,当请求携带凭证时,服务器必须明确返回Access-Control-Allow-Credentials: true头,否则浏览器会拒绝接收响应。全局与局部CORS配置冲突:
同时使用全局CORS(app, ...)和局部@cross_origin装饰器,可能导致配置叠加或冲突,尤其是局部装饰器缺少必要参数时。
解决步骤
1. 修正路由路径
修改auth.py中的所有路由定义,去掉重复的/api/auth前缀(蓝图已通过url_prefix添加该部分):
# 修改前 @auth_bp.route('/api/auth/register', methods=['POST']) # 修改后 @auth_bp.route('/register', methods=['POST'])
对login、logout、profile路由执行同样修改,确保最终接口路径与前端请求一致。
2. 更新CORS配置以支持凭证
在app.py中修改全局CORS配置,添加supports_credentials=True:
cors = CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000", "supports_credentials": True}})
若保留局部@cross_origin装饰器,需补充该参数:
@cross_origin(origins='http://localhost:3000', supports_credentials=True)
建议使用全局配置,避免重复代码。
3. 移除冗余局部装饰器
由于全局CORS配置已覆盖/api/*路径,auth.py中的@cross_origin装饰器属于冗余配置,可直接移除,避免冲突。
4. 验证预请求处理
使用curl测试OPTIONS预请求,确认响应头包含正确的CORS信息:
curl -X OPTIONS http://localhost:5000/api/auth/register -H "Origin: http://localhost:3000" -H "Access-Control-Request-Method: POST" -v
预期响应头应包含:
Access-Control-Allow-Origin: http://localhost:3000Access-Control-Allow-Credentials: true
5. 检查会话配置
确保Flask的SECRET_KEY已在Config类中正确配置,否则会话(session)无法正常工作,可能间接影响认证流程。
内容的提问来源于stack exchange,提问作者Amariah Kamau

