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.