从localhost:3000向127.0.0.1:5000发起Fetch请求的CORS错误解决问询
解决Flask与React跨域预检请求失败问题
原因分析
错误提示显示预检请求(OPTIONS)未返回HTTP 200 OK状态,尽管已启用flask-cors,但可能存在配置不明确、路由未处理OPTIONS方法或域名识别差异等问题。
修复方案
1. 显式配置CORS允许指定Origin
替换默认的CORS(app),明确指定前端Origin并开启凭证支持,确保预检请求被正确处理:
CORS(app, origins=["http://localhost:3000"], supports_credentials=True)
2. 手动处理OPTIONS请求
在路由中显式添加OPTIONS方法,并直接返回200状态码,解决预检不通过问题:
@app.route('/predict', methods=['POST', 'OPTIONS']) def predict(): if request.method == 'OPTIONS': return '', 200 # 原POST请求处理逻辑 sentence = request.json['message'] response = get_response(sentence) return jsonify({"response": response})
3. 统一前后端域名格式
浏览器会将localhost和127.0.0.1视为不同Origin,修改前端Fetch请求地址统一为localhost:
fetch('http://localhost:5000/predict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: "Hi" }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
4. 更新flask-cors版本
旧版本可能存在兼容性问题,执行升级命令:
pip install --upgrade flask-cors
验证步骤
- 重启Flask后端和React前端
- 重新发送请求,查看浏览器控制台是否仍有CORS错误
- 检查Network面板中OPTIONS请求的响应状态码是否为200,且包含正确的CORS响应头
内容的提问来源于stack exchange,提问作者Jerome Kansas
相关产品推荐
相关产品推荐

