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

Strapi v4:如何从自定义插件中添加全局中间件?

解决Strapi插件中添加全局中间件的问题

正确实现步骤

1. 统一导出插件中间件

在插件目录下创建server/middlewares/index.ts,将tags中间件纳入插件的中间件集合:

export { default as tags } from './tags';

2. 在插件入口注册并挂载全局中间件

修改server/index.ts,导出中间件集合,并通过Strapi的中间件系统正确挂载全局中间件:

import middlewares from './middlewares';

export default {
  register({ strapi }) {
    // 通过Strapi中间件系统获取已初始化的tags中间件实例
    const tagsMiddleware = strapi.middleware('plugin::tags-plugin.tags');
    // 挂载到全局服务,所有请求都会经过该中间件
    strapi.server.use(tagsMiddleware);
  },
  // 导出中间件集合,让Strapi识别插件的中间件资源
  middlewares,
  // 保留插件其他必要的导出项(如controllers、routes等)
  // controllers,
  // routes,
  // services,
};

3. 完善中间件业务逻辑

确保tags.ts的逻辑符合需求,比如识别目标content-type并处理Tags:

import { Strapi } from '@strapi/strapi';

const tags = (config, { strapi }: { strapi: Strapi }) => {
  return async (ctx, next) => {
    strapi.log.info('In tags middleware.');
    console.log('TAGS MIDDLEWARE');

    // 请求前:识别当前请求对应的content-type是否包含Tags字段
    const targetContentType = strapi.contentTypes[ctx.params.model || ctx.request.path.split('/')[2]];
    const hasTagsField = targetContentType?.attributes?.tags;

    if (hasTagsField) {
      // 可添加请求预处理逻辑,比如校验Tags参数
    }

    await next();

    // 请求后:若响应有效且目标content-type含Tags,注入相关数据
    if (hasTagsField && ctx.body) {
      // 示例:给响应结果追加Tags信息
      // ctx.body.tags = await strapi.service('plugin::tags-plugin.tags').getRelatedTags(ctx.body.id);
    }
  };
};

export default tags;

错误原因说明

  • 直接调用middlewares.tags仅能拿到中间件的工厂函数,未传入Strapi要求的config和strapi实例参数,导致中间件无法正常初始化。
  • 通过strapi.middleware('plugin::tags-plugin.tags')获取的是已完成初始化的中间件函数,Strapi会自动处理参数注入,确保中间件能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:35:20