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

Strapi自定义支付路由返回404问题求助

问题分析与解决方案

核心问题1:路由文件重复覆盖导出

你的路由文件中两次赋值module.exports,导致第一次导出的核心路由被完全覆盖,自定义路由也未与核心路由正确整合,Strapi无法识别该自定义路由。

原错误代码:

'use strict';
// @ts-ignore
const stripe = require("stripe")("sk_test_51H");

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::order.order'); // 此行被下方代码覆盖,完全无效

module.exports = {
    routes: [
        {
            method: "POST",
            path: "/orders/payment",
            handler: "order.setUpStripe"
        }
    ]
}

修复后的路由文件

使用createCoreRouter的extend方法合并自定义路由:

'use strict';
// @ts-ignore
const stripe = require("stripe")("sk_test_51H");

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::order.order', {
  extend: (router) => {
    router.post('/orders/payment', async (ctx) => {
      await strapi.controller('api::order.order').setUpStripe(ctx);
    });
    return router;
  }
});

或者直接合并核心路由与自定义路由:

'use strict';
const { createCoreRouter } = require('@strapi/strapi').factories;

const coreRouter = createCoreRouter('api::order.order');

module.exports = {
  ...coreRouter,
  routes: [
    ...coreRouter.routes,
    {
      method: "POST",
      path: "/orders/payment",
      handler: "order.setUpStripe"
    }
  ]
}

核心问题2:请求方法不匹配

你在浏览器地址栏直接访问http://localhost:1337/api/orders/payment时,发送的是GET请求,但路由定义的是POST方法,这会直接返回404。

测试方式修正

  • 使用Postman、Insomnia等工具发送POST请求到该地址,请求体中携带cart参数
  • 或在React前端用fetch/axios发送POST请求:
// Axios示例请求
axios.post('http://localhost:1337/api/orders/payment', {
  cart: [{ id: 1 }] // 替换为实际购物车数据
})
.then(res => console.log(res.data))
.catch(err => console.error(err));

额外优化点

  1. 控制器中total初始值错误,应改为数字类型:
let total = 0; // 原代码为字符串'',会导致reduce运算异常
  1. 为Promise.all中的catch添加日志,方便排查商品验证错误:
catch (error) {
  console.error('商品验证失败:', error);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:13:15