vue front-end code, axios for data interaction, login authentication code can not understand, config.headers.Authorization is a string "Bearer" +,! isn"t config.headers.Authorization always false, then when the request header can be added token, strange. During the whole process of running the program,! config.headers.Authorization has always been false, but when you jumped from the login page to the navigation page after a successful login, the config.headers.Authorization was added. I don"t know how to add it. Please explain
< hr > < H2 > export const baseURL =" http:xxxxxx/api/ "
var server = axios.create ({
baseURL: baseURL,
headers: {
Authorization: "Bearer " + window.sessionStorage.getItem("token") || ""
}
})
server.interceptors.request.use (function (config) {
if (! config.headers.Authorization) {
config.headers.Authorization = "Bearer " + window.sessionStorage.getItem("token") || ""
}
return config
})
server.interceptors.response.use (function (response) {
return response.data
}, function (error) {
if (error.response.status = 401) {
window.location.href = "/-sharp/login"
} else if (error.response.status = 403) {
return {
ok: false,
errMsg: i18n.t("error.errMsg") // ""
}
}
return Promise.reject (error)
handleLogin () {
this.$refs.loginForm.validate(async valid => {
if (valid) {
this.loading = true
try {
const result = await api.user.login(this.loginForm)
if (result.ok) {
window.sessionStorage.setItem("token", result.result.token)
this.$message.success("")
window.location.href = "/"
} else {
throw new Error(result.errMsg)
}
} catch (ex) {
this.$message.error(ex.message)
} finally {
this.loading = false
}
}
})
},
< hr >
< H2 > < AppLayoutMain.vue > < / H2 >
try {
await this.getUserInfo()
} catch (error) {
this.$message.error("")
this.$router.push("/login")
return
}
this.getShipInfo()