[SOLVED by metalsadman] Axios store needs browser reload
-
Hi guys,
This is my axios boot and all is good except i need to reload browser after login to get the token for the auth that i need to make API requests.What am i missing?
import axios from 'axios' const axiosInstance = axios.create({ baseURL: process.env.PROD ? 'https://XXXXXXXXXXXXXXXX' : 'http://127.0.0.1:4000', timeout: 1000, headers: { 'X-Client-App-Key': 'XXXXXXXXXXXXXXXX', 'Content-Type': 'application/json' } }) export default ({ store, Vue }) => { const token = store.state.auth.user.token if (token) { Vue.prototype.$axios = axiosInstance.defaults.headers.common['Authorization'] = 'Bearer ' + token } } export { axiosInstance }
-
Move your vue prototype registration out of the condition. Put it at bottom, and imo make your token assignment a function, so you can call assign/reassign that at a later time.
... export default ... ... token && setAuthHeader(token) Vue.prototype.$axios = axiosInstance ... } export const setAuthHeader = (token) => { axiosInstance... } ...
-
Ok, so now i have this:
export default ({ store, Vue }) => { const token = store.state.auth.user.token token && setAuthHeader(token) Vue.prototype.$axios = axiosInstance } export { axiosInstance } export const setAuthHeader = (token) => { axiosInstance.defaults.headers.common['Authorization'] = 'Bearer ' + token }
still need to reload browser but i guess i don’t doing it right?
-
Also, i’m running Quasar in SSR
-
Thank you @metalsadman for helping me, this works great i just had to ad the setAuthHeader upon login.
This is my working auth store action:
import { axiosInstance, setAuthHeader } from 'boot/axios' export const login = async (context, data) => { try { const res = await axiosInstance.post('api/auth/loggain', { email_address: data.email_address, password: data.password }) if (res.data.count) { console.log('error') } else { if (res.data.status === 'success') { const token = res.data.payload.token const user = res.data.user context.commit('setUser', { user, token }) setAuthHeader(token) <--------- THIS WAS ADDED return user } else { console.log(res.data.status) } } } catch (error) { return false } } export const logout = async function(context) { context.commit('clearUser') this.$router.push({ path: '/utloggad' }) }
Since i’m new to Quasar i’m sure you will find stuff that can be improved here
-
@PeterQF np, yeah thats what i meant making the setheader a function to be used at a later time, like after login was succesfull and a token is provided.
-
I solved this checkout If you like it please mark me
https://forum.quasar-framework.org/topic/2722/how-to-import-vuex-state-to-an-external-js/3