使用Stripe创建支付时遭遇No 'Access-Control-Allow-Origin' CORS错误
解决Stripe Checkout Session的CORS跨域问题
你的CORS错误根源是后端返回303重定向到Stripe Checkout地址,而前端通过Axios发起AJAX请求时,浏览器会自动跟进重定向,但Stripe的域名并未配置允许你的前端域名跨域,因此触发了CORS拦截。
1. 修改后端逻辑:返回Session URL而非重定向
将后端中返回重定向的代码替换为返回JSON格式的Session URL,让前端自行完成页面跳转:
try { const session = await stripe.checkout.sessions.create({ line_items: [ { price: `${priceId}`, // Replace with the Price ID quantity: 1, }, ], mode: 'payment', success_url: `${process.env.SUCCESSURL}?success=true`, cancel_url: `${process.env.FAILURL}?canceled=true`, // Stripe要求必填cancel_url,建议补上 }); // 替换重定向为返回JSON格式的Session URL return res.json({ url: session.url }); } catch (error) { console.log("error with payment checkout session: ", error); // 补充错误响应,让前端能捕获异常 return res.status(500).json({ error: error.message }); }
2. 完善CORS配置
由于前端请求携带了Authorization头,需要在CORS配置中明确允许该头及必要的请求方法,避免预请求(OPTIONS)失败:
app.use( cors({ origin: 'http://localhost:3000', credentials: true, allowedHeaders: ['Authorization', 'Content-Type', 'Accept'], methods: ['GET', 'POST', 'OPTIONS'] }) );
3. 前端代码保持现有逻辑即可
前端通过Axios拿到返回的url后,执行window.location = data.url是页面级跳转,不属于AJAX跨域范畴,因此不会触发CORS限制。
原方案报错原因
当后端返回303重定向时,Axios会自动发起第二个AJAX请求到Stripe的Checkout地址,这个请求的Origin依然是你的前端域名(http://localhost:3000),但Stripe的服务器并未设置Access-Control-Allow-Origin为你的域名,因此浏览器会拦截该请求,抛出CORS错误。
而让前端直接跳转是浏览器的正常页面导航行为,不受AJAX跨域规则约束,因此可以顺利进入Stripe的支付页面。
内容的提问来源于stack exchange,提问作者evan_tech1234
相关产品推荐
相关产品推荐

