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

Strapi报错:Cannot read properties of undefined (reading 'create') 求助

解决Strapi控制器报错:Cannot read properties of undefined (reading 'create')
  • 错误根源:你调用了不存在的strapi.services.order服务,你的集合是placed-orders,对应的Strapi服务标识符是api::placed-order.placed-order,而非order,导致服务对象为undefined,进而调用create方法时报错。

  • 修正步骤:

    1. 替换错误的服务引用:将strapi.services.order.create(data)改为strapi.service('api::placed-order.placed-order').create({ data: data })
      • 注意使用单数strapi.service()方法并传入完整的服务标识符
      • Strapi的服务create方法要求参数是包含data字段的对象,直接传原始请求体可能不符合格式要求
    2. 可选优化:如果需要保留核心控制器的默认逻辑(比如权限校验、响应格式),可以通过super.create(ctx)来扩展,而非完全重写:
      async create(ctx) {
          try {
              // 自定义逻辑,比如修改请求数据
              ctx.request.body = { ...ctx.request.body };
              // 调用核心create方法
              const response = await super.create(ctx);
              return { success: true, submission: response.data };
          } catch (err) {
              ctx.throw(500, err);
          }
      }
      
  • 修正后的完整控制器代码:

"use strict";

/**
 * placed-order controller
 */

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

module.exports = createCoreController('api::placed-order.placed-order', ({strapi})=>({
    async create(ctx) {
        try {
            const data = ctx.request.body;
            // 修正服务引用和参数格式
            const submission = await strapi.service('api::placed-order.placed-order').create({ data });
            return { success: true, submission };
        } catch (err) {
            ctx.throw(500, err);
        }
    },
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:55:20