Reputation: 1539
I have a token in the store, but I can't access it in my axios plugin. I used to simply import the store when using just Vue, really struggling to understand how to do this in Nuxt.js
I need to access a token value from my store, and use it in the 'Authorization' attribute below.
// /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,
})
As state is returned as a function from my store/index.js, I can't get this to work and clearly isn't the solution!
Looking at docs and at old posts on this it looks like I need to pass { store } as an argument but I get the error Cannot destructure property 'store' of 'undefined' as it is undefined.
For example...
export default ({ store }) => {
const api = axios.create({
baseURL: process.env.BASE_URL,
headers: {
Authorization: `Bearer` + store.state.token,
},
})
return api
}
I've also tried setting the Authorization header in the store itself as an alternative, but this doesn't have any effect when posting to my server, no authorization header is supplied.
// store/index.js
...
export const mutations = {
setToken(state, token) {
state.token = token
state.isUserLoggedIn = !!token
this.$axios.setHeader('Authorization', '123')
},
At a bit of loss with this and any help would be very much appreciated.
Upvotes: 0
Views: 4104
Reputation: 50798
Plugin functions should be pure and should not re-assign the value of $this
by using a =>
(fat arrow).
You can tap into the current $axios
instance and set the header whenever a request is made:
// plugins/axios.js
export default function ({ $axios, store }) {
$axios.onRequest(config => {
const { token } = store.state
if (token) {
config.headers.common.Authorization = `Bearer ${token}`
}
})
}
Mind you that $axios
is a package provided by @nuxtjs/axios
and this.$axios
will differ from this.axios
if you've manually registered axios
by its self.
Upvotes: 3