【发布时间】:2019-01-05 10:44:26
【问题描述】:
我有一个 Vue SPA,我使用 Axios 来处理请求,使用 vue-axios 来应用它,使用 vuex 来存储令牌。但是当我发送请求时,标头 Authorization 变为 Bearer undefined 或 Bearer null。
流程是,通过登录,我检索一个令牌,将其保存到会话存储中,分派一个登录操作,我的 vuex 存储将从会话存储中设置一个处于状态的令牌。在我的登录和路由器重定向到“/”之后,我想向 /foo 发送一个 GET 请求以及我的令牌。但是在这里我的令牌是未定义的。根据控制台日志,我知道会话存储在发送请求之前确实有令牌。
我正在遵循 Paweljw 的 this 教程中的结构:
Axios/axios.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://example.com/api/,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + sessionStorage.token
}
})
Axios/index.js
import Vue from 'vue';
import VueAxios from 'vue-axios';
import axios from './axios'
Vue.use(VueAxios, axios);
export default Vue;
组件/login.vue
onLogin(res) {
if (!res.data.token) {
return this.onLoginFailed();
}
sessionStorage.token = res.data.token;
this.$store.dispatch("login");
this.$router.replace(this.$route.query.redirect || "/");
组件/foo.vue
...
this.$http
.get("foo")
.then(res => this.doSomething(res))
.catch(() => this.doSomethingElse());
如前所述,这会发送一个带有 Bearer undefined 的请求。我知道当 axios.create(...) 被导出时 sessionStorage.token 为空 - 应用程序启动时尚未设置它。这可能就是原因,但我不明白我应该如何设置它,以及使用相同教程的其他人如何没有这个问题。
非常感谢任何建议。
【问题讨论】:
-
通过this package,您可以轻松创建axios实例并方便地从vue访问。