You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Axios POST请求遇CORS及500错误(Stripe支付场景)

问题解决:Stripe支付请求的CORS与500内部服务器错误

核心问题分析

你的两个错误是连锁关系:500内部服务器错误是根源——服务器端代码抛出未捕获异常,导致无法返回正确的CORS响应头,进而触发浏览器的跨域拦截。

1. 修复500内部服务器错误

云函数/payments/create路由存在明显代码逻辑错误:

app.post("/payments/create", async (request, response) => {
  console.log("Payment Request Received for this Amount: ", total);
  const total = request.query.total;
  // ... 其他代码
});

这里在声明total变量前就调用了它,会直接抛出ReferenceError: total is not defined,导致服务器返回500错误。

修复方案:

调整代码顺序,先获取变量再打印,同时增加异常捕获避免服务器崩溃:

app.post("/payments/create", async (request, response) => {
  try {
    const total = request.query.total;
    console.log("Payment Request Received for this Amount: ", total);

    const paymentIntent = await stripe.paymentIntent.create({
      amount: total,
      currency: "usd",
    });

    response.status(201).send({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (err) {
    response.status(500).send({ error: err.message });
    console.error("Payment creation error:", err);
  }
});

2. 解决CORS错误

服务器修复500错误后,CORS问题通常会自动解决——你的云函数已经配置了cors({ origin: true }),该配置会自动允许请求来源的跨域访问。如果仍有问题,检查以下两点:

  • 确认Axios实例使用正确:支付组件中需导入你自定义的Axios实例,而非默认Axios。当前代码用了axios({ ... }),若未导入自定义实例,会忽略baseURL配置,导致请求地址错误。
    修复支付组件的请求代码:

    // 先导入你的Axios实例(替换为实际文件路径)
    import axios from '../path/to/your/axios-instance';
    
    useEffect(() => {
        const getClientSecret = async () => {
          try {
            const response = await axios.post(`/payments/create?total=${getBasketTotal(basket) * 100}`);
            setClientSecret(response.data.clientSecret);
          } 
          catch (error) {
            console.log(error) // 现在能正常捕获错误
          }
        };
      
        getClientSecret();
    }, [basket]);
    
  • Firebase模拟器配置校验:确保模拟器的云函数端口与baseURL一致,且模拟器处于正常运行状态。

3. 额外检查项

  • 确认Stripe密钥已正确填入云函数代码,否则创建PaymentIntent会失败;
  • 检查getBasketTotal(basket)的返回值是否为合法数字,确保total是正确的分单位金额。

内容的提问来源于stack exchange,提问作者GuyWhoLikesToCode9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 07:55:12