I've encountered a problem where I have a token stored, but I'm struggling to access it in my axios plugin while using Nuxt.js. In the past with just Vue, it was simple to import the store and access the token. However, I'm having difficulty figuring out how to do this in Nuxt.js.
My goal is to retrieve the token value from my store and utilize it in the 'Authorization' attribute within the code snippet below.
Here is the current code I'm working with:
// /plugins/axios.js
import axios from 'axios'
import { state } from '../store'
export default () => {
const api = axios.create({
baseURL: process.env.BASE_URL,
headers: {
Authorization: `Bearer` + xxxx ACCESS STORE STATE HERE xxxx,
},
})
return api
}
// nuxt.config.js
...
{
plugins: ['~/plugins/persistedState.client.js', '~/plugins/axios'],
}
...
// store/index.js
export const state = () => ({
token: null,
user: null,
isUserLoggedIn: false,
})
Since the state is returned as a function within my store/index.js, I am unable to successfully implement this and it's becoming apparent that this isn't the correct solution!
What I have attempted so far
After reviewing documentation and old discussions on this topic, it seems like I need to pass { store } as an argument. However, I encountered an error message stating
Cannot destructure property 'store' of 'undefined' as it is undefined.
For instance...
export default ({ store }) => {
const api = axios.create({
baseURL: process.env.BASE_URL,
headers: {
Authorization: `Bearer` + store.state.token,
},
})
return api
}
I also experimented with setting the Authorization header directly within the store as another approach, but unfortunately, this didn't add any authorization header when making requests to the server.
// store/index.js
...
export const mutations = {
setToken(state, token) {
state.token = token
state.isUserLoggedIn = !!token
this.$axios.setHeader('Authorization', '123')
},
I'm currently feeling stuck on this issue and would greatly appreciate any assistance or guidance. Thank you.