Jinja模板中Fetch请求触发CORS错误问题求助
解决Flask跨域请求(CORS)失败问题
可能的原因及对应修复方案
1. 后端Flask-CORS配置未正确生效
即便指定了origins=['http://localhost:8000'],也可能因初始化方式错误导致配置未覆盖目标路由。
修复代码示例:
确保backend.py中正确初始化CORS,同时支持跨域请求携带验证令牌:
from flask import Flask, jsonify, request from flask_cors import CORS, cross_origin app = Flask(__name__) # 全局配置CORS,允许指定前端地址,支持携带凭证 CORS(app, origins=['http://localhost:8000'], supports_credentials=True) @app.route('/user', methods=['GET']) def get_user(): auth_token = request.headers.get('Authorization') # 此处添加令牌验证逻辑 return jsonify({'username': 'Miko', 'email': 'miko@example.com'}) if __name__ == '__main__': app.run(port=5000, debug=True)
若路由有自定义装饰器,可单独为该路由配置CORS:
@app.route('/user') @cross_origin(origins=['http://localhost:8000'], supports_credentials=True) def get_user(): # 业务逻辑代码
2. 前端Fetch请求配置不符合跨域要求
浏览器报错可能源于请求未正确设置凭证或请求头格式错误。
修复前端Fetch代码示例:
在user.html的JavaScript中调整请求配置:
fetch('http://localhost:5000/user', { method: 'GET', headers: { 'Authorization': 'Bearer ' + your_token, // 确保令牌格式正确(如Bearer前缀) 'Content-Type': 'application/json' }, credentials: 'include' // 跨域请求需携带凭证时必须设置 }) .then(response => { if (!response.ok) throw new Error('请求异常'); return response.json(); }) .then(data => { // 更新页面元素,例如显示用户名 document.getElementById('username').textContent = data.username; }) .catch(err => console.error('获取用户信息失败:', err));
3. 前端访问地址与配置的origin不匹配
确认前端实际访问地址严格等于http://localhost:8000,若使用127.0.0.1:8000访问,会因origin不匹配触发CORS拦截。
4. 浏览器缓存或插件干扰
清除浏览器缓存后重试,或使用无痕模式测试;暂时禁用广告拦截、隐私保护类插件,避免其拦截跨域请求。
验证步骤
- 打开浏览器开发者工具(F12),切换到Network标签,找到
/user请求; - 查看Response Headers,确认是否存在
Access-Control-Allow-Origin: http://localhost:8000; - 若响应头缺失,重新检查后端CORS配置;若存在仍报错,检查请求头的
Authorization格式是否正确。
内容的提问来源于stack exchange,提问作者Miko
相关产品推荐
相关产品推荐

