Nuxt gets the token value stored by vuex in other js files

topic description

finally, to develop a demo, using nuxt, there is a requirement to store the token value obtained after login in the header information of the http and put it on the Authorization field.

sources of topics and their own ideas

determine whether there is a token value in the axios interceptor through vuex storing token, and if so, set the token value to the Authorization field

related codes

/ / Please paste the code text below (do not replace the code with pictures)
store/index.js
import Vue from "vue"
import Vuex from" vuex"
Vue.use (Vuex)

const store = () = > new Vuex.Store ({
state: {

)
TOKEN: "", //token,headerAuthorization

},
mutations: {

SET_TOKEN: (state, token) => {
  debugger
  state.TOKEN = token;
}

},
getters: {

token(state) {
  return state.TOKEN
}

},
actions: {

login: ({commit}, {username, password}) => {
  fetch(process.env.baseUrl + "/auth",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        username,
        password
      })
    }
    ).then((res) => {
      if (res.status === 401) {
        throw new Error("Bad credentials")
      } else {
        return res.json()
      }
    })
    .then((res) => {
      if (res && res.data) {
        if (res.data.status == 0) {
          if (res.data.token) {
            commit("SET_TOKEN", res.data.token);
            sessionStorage.setItem("token", res.data.token);
          }
        }
      }
    })
}

}
});
export default store

plugins/axios.js
import axios from "axios"
import qs from" qs"
import store from". / store"
const service = axios.create ();
/ / POST pass parameter serialization
service.interceptors.request.use (
config = > {

)
let token = store().state.TOKEN;
console.log(token)
debugger;
if (token) {
  config.headers.Authorization = token
}
if (config.method === "post") {
  config.data = qs.stringify(config.data);
}
return config

},
error = > {

return Promise.reject(error)

}
)
/ / return status judgment
service.interceptors.response.use (
res = > {

)
debugger
return res.data

},
error = > {

debugger
return Promise.reject(error)

}
)

export default {
post (url, data) {

debugger
return service({
  method: "post",
  url,
  params: data
})

},
get (url, data) {

debugger;
return service({
  method: "get",
  url,
  params: data
})

},
delete (url, data) {

return service({
  methods: "delete",
  url,
  params: data
})

}
}

what result do you expect? What is the error message actually seen?

what I currently get in axios"s request interceptor is the default value of state, not the token value I set after I asked the login interface to get token.
1. This has nothing to do with the use of store () with parentheses, on the contrary, an error will be reported without parentheses in nuxt;
2. You can get the token value after setting in the vue file in pages. The console can also set it successfully, but you can"t get it in other js files.

if you are passing by, please take a look at how to get the changed token value in the interceptor of axios. Thank you very much.

Apr.01,2021

has been resolved on its own, and the final method adopted is js-cookie . There are two things that need to be changed:

.

1.store/index.js
sessionStorage.setItem ('token', res.data.token); replace it with Cookies.set (' token', res.data.token);
2.plugins/axios.js
let token = store (). State.TOKEN; replace with let token = Cookies.get ('token');
change the storage and access places to use Cookies

installation and reference are required before using js-cookie. For more information, stamp links ~


I don't quite understand it either. Can I paste a complete code?


the problem has been published for more than two years, and I am also worried that the same problem has been solved at last. I sent out my solution hoping to help more people like me

this is what I did:
introducing Axios and axios.js plug-ins into nuxt.config.js needless to say

  plugins: [
    { src: '~/plugins/axios.js' }
  ]
  modules: [
    '@nuxtjs/axios'
  ],

in axios.js:

import Vue from 'vue'

export default function ({ store, app: { $axios } }) {
  // :   !
  $axios.onRequest(config => {
    config.headers.common['user-token'] = store.state.userToken
  })
  // , 
  $axios.onResponse(res => {
    let data = res.data
    switch (data.code){
      case 500:
        if (data.message) {
          Vue.prototype.$message.error(data.message)
        } else {
          Vue.prototype.$message.error('')
        }
        break
      case -1:
        if (data.message) {
          Vue.prototype.$message.error(data.message)
        }
        store.commit('writeInToken', null)
    }
    return res.data
  })
  $axios.onError(error => {
    Vue.prototype.$message.error(`! `)
    return error
  })
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e9dbd9-690ef.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e9dbd9-690ef.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?