簡體   English   中英

插件的 Strapi v4 擴展服務器 API 不起作用

[英]Strapi v4 Extending Server API for Plugins does not work

我正在嘗試按照https://docs.strapi.io/developer-docs/latest/developer-resources/plugin-api-reference/server.html#entry-file上的 Strapi v4.0.0 指南擴展用戶 - permission plugin 來添加自定義路由/控制器,但目前為止一直沒有成功。 我按照文檔中的說明添加了自定義文件,但 UI 沒有變化。

我設法讓它在黃色突出顯示的正常 API 上工作,但無法為用戶權限插件這樣做

在此處輸入圖像描述

在以前的版本 3.6.8 中,此功能是通過擴展文件夾允許的。

我是否遺漏了新指南中的某些內容,我什至嘗試從node_modules > @strapi > plugin-users-permission復制文件並將新的路由和方法添加到現有的 controller 文件中,但它仍然沒有反映其中的部分中的更改我們為角色分配不同的路由權限。 用戶權限插件仍然顯示原始路由,沒有任何變化。

在此處輸入圖像描述

謝謝,

導出路由時,您需要導出類型,content-api 或 admin-api。 例如,查看 node_modules 中的 Strapi email 插件,更改路由文件夾中的文件夾和文件結構以匹配,然后您將能夠在管理面板中設置權限。

我在研究幾乎相同的問題時遇到了這個線程,我想分享我的解決方案。

首先,我發現這部分文檔比您引用的文檔更有用: https://docs.strapi.io/developer-docs/latest/development/plugins-extension.html

我的目標是根據此處的評論編寫一條新路線來驗證 JWT 令牌: https://github.com/strapi/strapi/issues/3601#issuecomment-510810027但已針對 Strapi v4 更新。

解決方案很簡單:

  1. 創建一個新的文件夾結構: ./src/extensions/user-permissions如果它不存在。
  2. 如果不存在,則創建一個新文件./src/extensions/user-permissions/strapi-server.js
  3. 將以下內容添加到文件中:
module.exports = (plugin) => {
  plugin.controllers.<controller>['<new method>'] = async (ctx) => {
    // custom logic here
  }

  plugin.routes['content-api'].routes.push({
    method: '<method>',
    path: '/your/path',
    handler: '<controller>.<new method>',
    config: {
      policies: [],
      prefix: '',
    },
  });

  return plugin;
};

如果您不確定可用的控制器,您可以隨時查看 API 文檔或console.log(plugin)console.log(plugin.controllers)

管理服務器重新啟動后,您應該會在用戶權限部分下看到您所期望的新路由,並且您可以根據需要為其分配權限。

我的完整strapi-server.js文件包括驗證 JWT 的邏輯:

module.exports = (plugin) => {
  plugin.controllers.auth['tokenDecrypt'] = async (ctx) => {
    // get token from the POST request
    const {token} = ctx.request.body;

    // check token requirement
    if (!token) {
      return ctx.badRequest('`token` param is missing')
    }

    try {
      // decrypt the jwt
      const obj = await strapi.plugin('users-permissions').service('jwt').verify(token);

      // send the decrypted object
      return obj;
    } catch (err) {
      // if the token is not a valid token it will throw and error
      return ctx.badRequest(err.toString());
    }
  }

  plugin.routes['content-api'].routes.push({
    method: 'POST',
    path: '/token/validation',
    handler: 'auth.tokenDecrypt',
    config: {
      policies: [],
      prefix: '',
    },
  });

  return plugin;
};

如果您的 Strapi 服務器使用 Typescript,請確保相應地命名您的擴展文件。 因此,您需要將文件strapi-server.ts而不是strapi-server.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM