Warm tip: This article is reproduced from serverfault.com, please click

Strapi / Nuxt

发布于 2020-11-30 17:16:16

I've used this to setup auth in strapi and nuxt: Auth with Strapi and Nuxt

I'm currently trying to retrieve the items specific to a authenticated user (already checked out this strapi - restrict user to fetch only data related to him). To do this I created a custom route in Strapi (/api/routine/config/routes.json):

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

and a custom controller (/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);
  },
};

I already gave permission through Strapi admin for authenticated users to access 'me'. When I hit the endpoint from Nuxt:

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

I get this error:

GET http://localhost:1337/routines/me 404 (Not Found)

Why is the custom route not found? Am I using the wrong endpoint?

Questioner
joedoesnotknow
Viewed
0
joedoesnotknow 2020-12-08 07:16:28

It was a fault in my Strapi routes config. Answer was provided through the amazingly helpful Strapi forums: 403 forbidden when calling custom controller from Nuxt

Here is the problem:

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

So basically you are hitting the first route right now and it assumes that me is actually an :id. Koa is making the verifications with regex so in this case it takes the first matched route. Move the route with /me above that one with /:id