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

如何搭建Node.js接口实现React对WooCommerce订单的CRUD操作

实现React可调用的WooCommerce订单接口路由

核心改动说明

你需要在现有server.js中添加API路由、请求体解析中间件,完善CORS配置,同时实现GET(获取)、PUT(更新)、DELETE(删除)三个核心接口,供React端调用。

修改后的完整server.js代码

import express from 'express';
import cors from 'cors';
import pkg from '@woocommerce/woocommerce-rest-api';
const WooCommerceRestApi = pkg.default;

const PORT = 5000;
const app = express();

// 配置CORS(生产环境建议替换为指定前端域名)
const corsOptions = {
  origin: "*"
};
app.use(cors(corsOptions));

// 解析JSON格式的请求体,处理PUT请求的更新参数
app.use(express.json());

// 初始化WooCommerce API客户端
const WooCommerce = new WooCommerceRestApi({
  url: "https://myste.com/", // 补全HTTP协议前缀
  consumerKey: "ck_4xxxxxxxxxxxxxxxxxxxxx",
  consumerSecret: "cs_xxxxxxxxxxxxxxxxxxxxxx",
  version: 'wc/v3'
});

// 1. 获取所有订单接口
app.get('/api/orders', async (req, res) => {
  try {
    const response = await WooCommerce.get("orders");
    res.status(200).json(response.data);
  } catch (error) {
    res.status(error.response?.status || 500).json(error.response?.data || { message: '获取订单失败' });
  }
});

// 2. 更新指定订单接口
app.put('/api/orders/:id', async (req, res) => {
  const { id } = req.params;
  const updateData = req.body;

  try {
    const response = await WooCommerce.put(`orders/${id}`, updateData);
    res.status(200).json(response.data);
  } catch (error) {
    res.status(error.response?.status || 500).json(error.response?.data || { message: '更新订单失败' });
  }
});

// 3. 删除指定订单接口
app.delete('/api/orders/:id', async (req, res) => {
  const { id } = req.params;

  try {
    const response = await WooCommerce.delete(`orders/${id}`);
    res.status(200).json({ message: '订单删除成功', data: response.data });
  } catch (error) {
    res.status(error.response?.status || 500).json(error.response?.data || { message: '删除订单失败' });
  }
});

app.listen(PORT, () => {
  console.log(`服务运行在 http://localhost:${PORT}`);
});

关键细节说明

  • express.json()中间件:必须配置才能解析React发送的JSON请求体,比如PUT请求的订单更新参数。
  • 异步路由处理:用async/await替代Promise链式调用,代码更简洁易维护。
  • 错误状态返回:每个路由捕获API调用异常,返回对应HTTP状态码和错误信息,方便React端做异常处理。
  • 接口路径规范:统一用/api/orders前缀,便于前端识别和管理接口。

React端调用示例(参考)

// 获取所有订单
const fetchOrders = async () => {
  const res = await fetch('http://localhost:5000/api/orders');
  const data = await res.json();
  console.log(data);
};

// 更新订单(示例:修改订单状态为已完成)
const updateOrder = async (orderId) => {
  const res = await fetch(`http://localhost:5000/api/orders/${orderId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ status: 'completed' })
  });
  const data = await res.json();
  console.log(data);
};

// 删除订单
const deleteOrder = async (orderId) => {
  const res = await fetch(`http://localhost:5000/api/orders/${orderId}`, {
    method: 'DELETE'
  });
  const data = await res.json();
  console.log(data);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:45:47