React对接Flask+Stripe遇403预请求失败且无法自动跳转求助
问题解决步骤
1. 修复前端请求头错误
前端请求中无需携带Access-Control-Allow-Origin头——这是服务器返回的响应头,前端发送该头会触发不必要的预请求校验,直接导致403错误。修改后的React代码:
function buy() { window.scroll(0, 0); fetch(`${IP}/init_checkout`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ price_id: 'my_stripe_product_price', }), }) .then(res => { if (res.ok) return res.json(); return res.json().then(json => Promise.reject(json)); }) .then(({ url }) => { window.location.href = url; }) .catch(e => { console.error(e.error); }); }
2. 修复Flask的CORS配置与返回逻辑
- 明确允许OPTIONS预请求(浏览器跨域前会自动发送OPTIONS请求校验)
- 不要返回重定向:fetch会自动跟随重定向,无法直接拿到Stripe的结账URL,改为返回包含URL的JSON让前端手动跳转
修改后的Flask代码:
from flask import jsonify, request from flask_cors import cross_origin import stripe # 请替换为你的Stripe密钥 stripe.api_key = "your_stripe_secret_key" @app.route('/init_checkout', methods=['POST', 'OPTIONS']) @cross_origin(origin="*", headers=["Content-Type"]) def init_checkout(): # 处理OPTIONS预请求 if request.method == 'OPTIONS': return '', 200 data = request.get_json() price_id = data.get('price_id') if not price_id: return jsonify({'error': {'message': '缺少price_id参数'}}), 400 try: checkout_session = stripe.checkout.Session.create( success_url='http://localhost:3000', cancel_url='http://localhost:3000/form', payment_method_types=[ 'card', 'sepa_debit', 'sofort', 'ideal' ], mode='subscription', line_items=[{ 'price': price_id, 'quantity': 1 }], ) return jsonify({'url': checkout_session.url}) except Exception as e: print(str(e)) return jsonify({'error': {'message': str(e)}}), 400
核心问题说明
- Preflight 403错误:前端错误携带响应头字段,加上Flask未处理OPTIONS预请求,双重原因导致校验失败,修正请求头并配置OPTIONS处理即可解决。
- 跳转失败:原逻辑返回303重定向,fetch会自动跳转到Stripe页面,前端无法捕获URL执行跳转;改为返回JSON格式的URL,让前端通过
window.location.href手动跳转即可正常工作。
内容的提问来源于stack exchange,提问作者Ryan Gannon
相关产品推荐
相关产品推荐

