【问题标题】:Strapi / Nuxt - Can't find custom routeStrapi / Nuxt - 找不到自定义路线
【发布时间】:2021-03-12 15:26:55
【问题描述】:

我用它在strapi和nuxt中设置身份验证: Auth with Strapi and Nuxt

我目前正在尝试检索特定于经过身份验证的用户的项目(已签出此strapi - restrict user to fetch only data related to him)。为此,我在 Strapi (/api/routine/config/routes.json) 中创建了一个自定义路由:

{
  "method": "GET",
  "path": "/routines/me",
  "handler": "Routine.me",
  "config": {
    "policies": []
  }
}

和一个自定义控制器 (/api/controllers/Routine.js):

module.exports = {
  me: async (ctx) => {
    const user = ctx.state.user;
    if (!user) {
      return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
    }

    const data = await strapi.services.routine.find({user:user.id});  

    if(!data){
      return ctx.notFound();
    }

    ctx.send(data);
  },
};

我已经通过 Strapi 管理员授予经过身份验证的用户访问“我”的权限。当我从 Nuxt 到达终点时:

const 例程 = await axios.get(http://localhost:1337/routines/me)

我收到此错误:

GET http://localhost:1337/routines/me 404(未找到)

为什么找不到自定义路由?我是否使用了错误的端点?

【问题讨论】:

    标签: authentication routes nuxt.js strapi


    【解决方案1】:

    也许您已经解决了,但您似乎忘记了在请求中发送身份验证标头。

        const routines = await axios.get(
            'http://localhost:1337/routines/me', {
                headers: {
                    Authorization:
                    this.$auth.getToken('local'),
                },
            }
    

    【讨论】:

    • 谢谢@user3195845,我错过了标题!我现在收到一个 403 禁止错误:GET localhost:1337/routines/me 403 (Forbidden)。这与我的 Strapi 配置有关吗?我用你的提示更新了代码,除了我必须使用上下文来访问身份验证,因为我使用的是 asyncData(): 'Authorization': context.app.$auth.getToken('local')
    • 乐于助人 :) 好像您没有通过身份验证?您确定令牌随请求一起传递吗?如果你删除第一个 if 语句 if(!user) 你得到任何结果会发生什么?
    • 它给出了相同的结果:403(禁止)。看来我已通过身份验证,如果我在发送请求之前记录 this.$auth.getToken('local') 它会打印出不记名令牌。我认为您是对的,并且以某种方式未随请求正确发送标头。你知道为什么吗?
    【解决方案2】:

    这是我的 Strapi 路由配置中的一个错误。答案是通过非常有用的 Strapi 论坛提供的: 403 forbidden when calling custom controller from Nuxt

    问题来了:

    {
      "method": "GET",
      "path": "/routines/:id",
      "handler": "routine.findOne",
      "config": {
        "policies": []
      }
    },
    {
      "method": "GET",
      "path": "/routines/me",
      "handler": "routine.me",
      "config": {
        "policies": []
      }
    

    所以基本上你现在正在走第一条路线,它假设 我实际上是一个:id。 Koa 正在使用正则表达式进行验证,因此在这种情况下,它采用第一个匹配的路线。将带有 /me 的路线移到带有 /:id 的路线上方

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2019-08-01
      • 2018-06-04
      • 2019-07-05
      • 1970-01-01
      • 2021-09-04
      • 2012-08-23
      相关资源
      最近更新 更多