React+Rails跳转Stripe客户门户遭遇CORS跨域错误求助
解决Stripe客户门户跳转的CORS错误问题
问题原因
你通过axios发起AJAX请求调用Rails后端,后端直接重定向到Stripe客户门户URL。但AJAX请求受CORS规则约束,Stripe域名不会为你的localhost添加Access-Control-Allow-Origin响应头,浏览器因此拦截了重定向请求导致报错。直接在浏览器打开链接正常,是因为这属于浏览器顶层导航,不受AJAX的CORS限制。
解决方案
1. 修改Rails控制器,返回JSON格式的会话URL
放弃直接重定向,将Stripe生成的会话URL以JSON形式返回给前端:
class CustomerPortalController < ApplicationController before_action :authenticate_user! def create @user = current_user @company_profile = @user.company_profile @customer_id = @company_profile.customer_id session = Stripe::BillingPortal::Session.create({ customer: @customer_id }) # 返回JSON格式的URL,替代重定向逻辑 render json: { portal_url: session.url }, status: :ok end end
2. 修改React前端,接收URL并执行页面跳转
在axios请求的回调中获取返回的URL,通过window.location.href完成跳转——这是浏览器顶层导航,不会触发CORS限制:
import React from 'react'; import axios from 'axios'; import { authToken } from 'Helpers/authToken'; function ManageSubscription(){ const url = '/customer_portal'; const handlePortal = async (e) => { e.preventDefault(); try { const response = await axios.post(url, {}, { headers: { 'X-CSRF-Token': authToken, Accept: 'application/json' } }); // 跳转到Stripe客户门户 window.location.href = response.data.portal_url; } catch (error) { console.error('获取客户门户链接失败:', error); } } return( <div className="subscription-top-wrapper"> <div className="customer-portal-row"> <button onClick={handlePortal} className="button-33 w-button" > Manage Your Subscription </button> </div> </div> ); }
额外说明
- 修正了你之前axios请求的参数错误:
axios.post的第二个参数是请求体,headers需放在第三个参数的配置对象中,之前的写法会把headers当成请求体发送,可能导致后端CSRF验证失败。 - 保持现有rack-cors配置即可,它已正确处理前端与Rails后端之间的CORS问题。
内容的提问来源于stack exchange,提问作者John Gerard
相关产品推荐
相关产品推荐

