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

React调用WooCommerce WordPress API获取商品数据失败求助

问题修复步骤

1. 解决moment未找到的错误

  • 若实际需要moment库,执行安装命令:npm install moment
  • 若代码中未使用该库,直接删除import moment from "moment";这一行

2. 解决Node核心模块(stream、buffer)缺失的问题

Webpack 5不再默认提供Node.js核心模块的polyfill,而@woocommerce/woocommerce-rest-api依赖这些模块,需手动配置:

  • 安装所需polyfill包:
    npm install stream-browserify buffer
    
  • 若使用Create React App,需通过craco修改Webpack配置(CRA默认隐藏Webpack配置):
    1. 安装craco:npm install @craco/craco --save-dev
    2. 在项目根目录创建craco.config.js,内容如下:
      module.exports = {
        webpack: {
          configure: {
            resolve: {
              fallback: {
                "stream": require.resolve("stream-browserify"),
                "buffer": require.resolve("buffer/")
              }
            }
          }
        }
      };
      
    3. 修改package.json中的scripts,替换react-scripts为craco:
      "scripts": {
        "start": "craco start",
        "build": "craco build",
        "test": "craco test"
      }
      

3. 解决api未定义的错误

你初始化的WooCommerce API实例变量名为API_URL,但调用时用了api,变量名不匹配,同时存在接口路径错误:

  • 统一变量名,修正API初始化的URL(只需站点根URL,无需追加接口路径):
    const api = new WooCommerceRestApi({
      url: "https://test.local",
      consumerKey: "ck_5367a6bdaa476696355c156231b735eb98b46001",
      consumerSecret: "cs_f365c03bf06be03b87bff11e7d17220eb29531f1",
      version: "wc/v3"
    });
    
  • 修正接口路径:.get("product")改为.get("products"),WooCommerce商品列表的正确端点是/products

4. 其他潜在问题优化

  • 本地开发需解决跨域问题:在WordPress站点安装CORS插件(如WP CORS),或在主题functions.php中添加CORS响应头
  • 消费者密钥/密钥不要硬编码到代码中,建议用环境变量管理(如process.env.REACT_APP_WC_CONSUMER_KEY)
  • 不要留空catch块,添加错误日志便于调试

修正后的完整代码
import { Table } from "react-bootstrap";
import { useEffect, useState } from "react";
import "./App.css";
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const api = new WooCommerceRestApi({
  url: "https://test.local",
  consumerKey: "ck_5367a6bdaa476696355c156231b735eb98b46001",
  consumerSecret: "cs_f365c03bf06be03b87bff11e7d17220eb29531f1",
  version: "wc/v3"
});

function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = () => {
    api
      .get("products", {
        per_page: 20,
      })
      .then((response) => {
        if (response.status === 200) {
          setProducts(response.data);
        }
      })
      .catch((error) => {
        console.error("获取商品数据失败:", error);
      });
  };

  return (
    <div className="App">
      <Table striped bordered hover>
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>
          {products.map((liveProduct) => {
            return (
              <tr key={liveProduct.id}>
                <td>{liveProduct.id}</td>
                <td>{liveProduct.name}</td>
                <td>{liveProduct.description}</td>
                <td>{liveProduct.price}</td>
              </tr>
            );
          })}
        </tbody>
      </Table>
    </div>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:36:18