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

TypeError:读取'map'时无法读取undefined属性及Stripe结算异常排查

问题解决:TypeError与Stripe结算商品显示异常

一、TypeError: Cannot read properties of undefined (reading 'map') 原因及修复

错误根源

  1. Stripe字段拼写错误:server.js中创建会话时使用了line_item,正确的字段名应为line_items(复数形式)。这个错误会导致Stripe API解析失败,同时触发req.body.items的读取异常。
  2. 请求体数据未正确传递:checkout.js中当前items是注释后的空数组,若前端未收集用户选中的商品并传递,会导致req.body.items为undefined,调用map时直接报错。
  3. 价格配置错误:代码中用storeItem.priceId(Stripe价格ID)赋值给unit_amount,但unit_amount需要传入以分为单位的金额数值,正确做法是直接使用price字段指定Stripe的价格ID,无需手动构建price_data。

修复后的server.js核心代码

app.post("/create-checkout-session", async (req, res) => {
  // 校验商品是否存在,提前拦截空请求
  if (!req.body.items || req.body.items.length === 0) {
    return res.status(400).json({ error: "未选中任何商品" });
  }

  const session = await stripe.checkout.sessions.create({
    // 修正字段名为line_items
    line_items: req.body.items.map((item) => {
      const storeItem = storeItems.get(item.id);
      return {
        // 直接使用Stripe价格ID,无需手动构建价格数据
        price: storeItem.priceId,
        quantity: item.quantity || 1,
      };
    }),
    mode: "payment",
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/cancel.html`,
    automatic_tax: { enabled: true },
  });

  res.redirect(303, session.url);
});

二、Stripe结算显示所有商品的问题修复

当前checkout.js的items是固定空数组,需要改为动态收集用户选中的购物车商品:

修复后的checkout.js代码

// 全局变量存储用户选中的购物车商品
let cartItems = [];

// 示例:商品加入购物车的逻辑(根据你的实际UI调整)
function addToCart(itemId) {
  const existingItem = cartItems.find(item => item.id === itemId);
  if (existingItem) {
    existingItem.quantity += 1;
  } else {
    cartItems.push({ id: itemId, quantity: 1 });
  }
}

const button = document.getElementById("checkout-button");
button.addEventListener("click", () => {
  fetch("/create-checkout-session", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    // 传递用户实际选中的购物车商品
    body: JSON.stringify({ items: cartItems }),
  })
    .then((res) => {
      if (res.ok) return res.json();
      return res.json().then((json) => Promise.reject(json));
    })
    .then(({ url }) => {
      window.location = url;
    })
    .catch((e) => {
      console.error(e.error);
    });
});

额外注意事项

  • 确保storeItems中的priceId是Stripe后台创建的有效价格ID,每个商品对应正确的价格条目。
  • 前端需完善购物车的添加/删除逻辑,保证cartItems始终同步用户的选中状态。
  • 后端的校验逻辑避免了空请求导致的服务端错误,提升了代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:30:17