You need to enable JavaScript to run this app. 本地运行Stripe Checkout示例出现CORS跨域错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

本地运行Stripe Checkout示例出现CORS跨域错误如何解决?

问题根源

该CORS报错是前端请求逻辑错误导致的:fetch请求默认会自动跟进3xx重定向响应,你后端接口返回303跳转到Stripe Checkout地址后,fetch会直接发起跨域AJAX请求Stripe的页面,而Stripe的公共页面本身不允许跨域AJAX调用,自然就返回预检403和CORS报错。


修复步骤

1. 调整后端配置与逻辑

首先你配置的https://checkout.stripe.comCORS规则完全无效:后端调用Stripe接口属于服务端请求,不受CORS规则限制,CORS仅需要配置你自己的前端访问地址即可。同时不要在后端直接做重定向,把Checkout会话地址返回给前端处理:

const express = require("express");
const app = express();
const cors = require("cors");

const stripe = require("stripe")(
  process.env.STRIPE_SECRET_KEY
);
// CORS仅配置你的前端地址即可
app.use(
  cors({
    origin: "http://localhost:8000"
  })
);
// 新增JSON解析中间件,后续传参可正常解析
app.use(express.json())

app.post("/create-checkout-session", async (req, res) => {
  console.log('getting here 1')
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: "T-shirt",
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: "http://localhost:8000/success", // 替换为你的前端成功回调页地址
    cancel_url: "http://localhost:8000/cancel", // 替换为你的前端取消回调页地址
  });
  
  console.log('getting here 2')
  // 删掉原redirect逻辑,返回Checkout地址给前端
  res.json({ checkoutUrl: session.url })
});

app.listen(4242, () => console.log(`Listening on port ${4242}!`));

2. 调整前端请求逻辑

fetch拿到返回的Checkout地址后,直接做整页跳转即可,不要用fetch处理重定向:

handleClick = async () => {
  const res = await fetch(`${process.env.BACKEND_API_URL}/create-checkout-session`, {
    method: 'POST'
  })
  const { checkoutUrl } = await res.json()
  // 整页跳转到Stripe Checkout页
  window.location.href = checkoutUrl
}

补充说明

Stripe Checkout本身设计就是需要整页跳转访问的,不要用AJAX方式请求对应的地址,所有和Stripe的核心交互都由后端用密钥调用服务端接口完成,前端只负责拿到地址后跳转即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 11:30:04