MaxPower
MaxPower

Reputation: 31

Strapi API gives 401 for authenticated user with Nuxt/Strapi module

Just trying to learn yet another framework here :D

I'm using Nuxt with Strapi and MongoDB. For cutting the corners (dont' hate the player..) I've installed the Nuxt/Strapi module => https://strapi.nuxtjs.org/

I get the collection data from Strapi ok when I'm not authenticated, but when the user is authenticated (basic strapi roles), then Strapi throws 401 error for the collection data. The collection is open for public aswell as for authenticated users in roles & permissions. So there should not be issues from Strapi end.

I get and can log the JWT token from Strapi and the user is logged in/authenticated properly. To my best knowledge (it's kinda badly documented) the Nuxt/Strapi module should pass the JWT token in the header and authentication should work out of the box for REST calls? At least the code works when not authenticated:

async fetch() {
    this.building = await this.$strapi.find('building');
},
data() {
  return {
    building: []
  }
}

When authenticated the console logs these errors:

index.js?d823:434 GET http://localhost:1337/building 401 (Unauthorized)

fetch.client.js?2293:75 Error in fetch(): HTTPError: Schema hasn't been registered for model "user".
Use mongoose.model(name, schema)

I'm new to this stack so I'm kinda lost what's wrong.

The onlyt thing I could find close to related to this issues was this thread: Mongoose Schema hasn't been registered for model

This is very basic functionality and must of been tested, so I don't think that this kinda bug can slip into the module. It's more likely I'm just doing somtething wrong.

Thanks in advance!

Upvotes: 0

Views: 2543

Answers (1)

Cristian Parada
Cristian Parada

Reputation: 40

You must first authenticate, or use a public user, for authenticate first call /auth/local you will get a token in response, use it in the headers of your fetch. check this:

import axios from 'axios';

const { data } = await axios.post('http://localhost:1337/auth/local', {
//your user
  identifier: '[email protected]',
  password: 'strapi',
});

console.log(data);

to fetch

import axios from 'axios';

const { data } = await axios.get('http://localhost:1337/articles', {
  headers: {
    Authorization:
      'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTc2OTM4MTUwLCJleHAiOjE1Nzk1MzAxNTB9.UgsjjXkAZ-anD257BF7y1hbjuY3ogNceKfTAQtzDEsU',
  },
});

change the long token for the previous saved token

Upvotes: 1

Related Questions