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

React与Node集成Stripe时后端无法解构items问题求助

React+Stripe支付集成:后端无法获取前端传递的items参数问题排查与解决

问题背景

按照Stripe官方文档实现React与Node的Stripe支付集成时,前端通过fetch向后端传递items参数,但后端无法从req.body中解构出items,同时存在金额参数传递错误的问题。

相关代码

Node后端代码

app.post("/create-payment-intent", async (req, res) => {
  try {
      const { items } = req.body;
      console.log(items);

    const paymentIntent = await stripe.paymentIntents.create({
      currency: "gbp",
      amount: items,
      automatic_payment_methods: { enabled: true },
    });

    res.send({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (err) {
    // 原代码缺失错误处理
  }
});

React前端代码

useEffect(() => {
  fetch("/create-payment-intent", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({items: [{ price: totalAmount }]}),
  }).then(async (result) => {
    var { clientSecret } = await result.json();
    setClientSecret(clientSecret);
  });
}, [totalAmount]);

问题原因分析

  1. 未配置JSON请求体解析中间件:Express默认不会解析JSON格式的请求体,导致req.body为空,自然无法解构出items。
  2. 金额参数类型错误:即使成功获取items,直接将数组传给paymentIntents.create的amount参数也不符合Stripe要求——amount必须是对应货币最小单位的整数(例如英镑需传入便士数,10英镑对应1000)。

解决步骤

1. 后端添加JSON解析中间件

在Express应用中添加express.json()中间件,确保能解析前端发送的JSON请求体:

const express = require('express');
const app = express();

// 务必在路由定义之前添加此中间件
app.use(express.json());

2. 正确处理金额参数

从items中提取金额,转换为最小货币单位的整数后再传给Stripe:

app.post("/create-payment-intent", async (req, res) => {
  try {
    const { items } = req.body;
    console.log(items); // 现在可以正常获取前端传递的数组

    // 计算总金额并转换为便士(英镑最小单位)
    const totalAmount = items.reduce((sum, item) => {
      // 假设item.price是英镑的浮点数,例如10.50,乘以100后取整
      return sum + Math.round(item.price * 100);
    }, 0);

    const paymentIntent = await stripe.paymentIntents.create({
      currency: "gbp",
      amount: totalAmount, // 传入整数金额
      automatic_payment_methods: { enabled: true },
    });

    res.send({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (error) {
    // 添加错误处理,返回异常信息给前端
    res.status(500).send({ error: error.message });
  }
});

3. 前端补充错误处理(可选但推荐)

添加请求失败时的错误捕获,方便排查问题:

useEffect(() => {
  fetch("/create-payment-intent", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ items: [{ price: totalAmount }] }),
  }).then(async (result) => {
    if (!result.ok) {
      const errorData = await result.json();
      console.error("创建支付意图失败:", errorData);
      return;
    }
    const { clientSecret } = await result.json();
    setClientSecret(clientSecret);
  }).catch(networkError => {
    console.error("网络请求错误:", networkError);
  });
}, [totalAmount]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:05:23