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

React对接Stripe时,如何向Node.js Express后端传递支付金额?

我来帮你搞定这个问题!你遇到的核心问题是前后端的数据格式没有同步匹配——原来的代码用纯文本传递token ID,现在要传包含金额的JSON对象,就得同时修改前后端的解析规则和请求格式,具体解决方案如下:

关键修改思路

  1. 后端要切换到JSON解析模式,因为现在接收的是结构化的JSON数据,不再是纯文本
  2. 前端要正确设置请求头并序列化JSON数据,同时注意属性名的大小写(JavaScript是大小写敏感的!)

修改后的完整代码

后端 server.js

// server.js
const app = require("express")();
const stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
// 替换原有的text解析器为JSON解析器
app.use(require("body-parser").json());

app.post("/charge", async (req, res) => {
  try {
    // 从JSON请求体中获取前端传来的金额和token ID
    let {status} = await stripe.charges.create({
      amount: req.body.amount,
      currency: "usd",
      description: "An example charge",
      source: req.body.tokenId // 注意属性名要和前端完全一致
    });
    res.json({status});
  } catch (err) {
    // 优化错误返回,方便前端调试
    res.status(500).json({error: err.message});
  }
});

前端提交方法

async submit(ev) {
  ev.preventDefault(); // 记得阻止表单默认提交行为,避免页面刷新
  try {
    let {token} = await this.props.stripe.createToken({name: "Name"});
    // 这里的金额可以从组件状态/输入框中动态获取,示例用2000
    const paymentAmount = 2000;
    
    let response = await fetch("/charge", {
      method: "POST",
      headers: {
        "Content-Type": "application/json" // 明确告诉后端是JSON格式
      },
      // 必须把对象序列化为JSON字符串
      body: JSON.stringify({ 
        amount: paymentAmount,
        tokenId: token.id // 注意是token.id,不是token.Id(大小写错误)
      })
    });

    if (response.ok) {
      const result = await response.json();
      console.log("Purchase Complete!", result);
    } else {
      const error = await response.json();
      console.error("Purchase failed:", error);
    }
  } catch (err) {
    console.error("Payment process error:", err);
  }
}

几个容易踩坑的细节

  • 请求头与解析器匹配:前端设置Content-Type: application/json,后端必须用body-parser.json(),否则后端无法正确解析请求体,会返回undefined
  • 属性名大小写敏感:前端传的是tokenId,后端就不能写成tokenid;token的ID是token.id(小写i),别写成token.Id
  • 错误处理优化:添加try/catch捕获前端异步错误,后端返回具体错误信息,方便调试定位问题
  • 阻止默认行为:表单提交时一定要调用ev.preventDefault(),否则页面会刷新,导致请求中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:57:32