【问题标题】:Set axios authorization header depends on store changes设置 axios 授权头依赖于 store 的变化
【发布时间】:2018-08-23 14:52:30
【问题描述】:

我是 Vue 的新手(我是一个反应型的人),我遇到了这个问题。

axios.js

import store from '../../store/index';
import axios from 'axios'

const API_URL = process.env.API_URL;
const token = store.getters.auth.token;

export default  axios.create({
baseURL: API_URL,
headers: {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${token}`
 }
})

存储/index.js

import auth from './modules/auth'

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({

  state: {},
  getters : {},
  mutations: {},
  actions:{},

  modules: {
    auth
  },
  strict: debug,
})

模块/授权

import { AUTH_SUCCESS, AUTH_GUEST } from '../actions/auth'
import axios from '../../util/axios/axios'
import Vue from "vue";

const state = {
  token: localStorage.token || '',
};

const getters = {
  token: state => state.token
};

const actions = {
  [AUTH_GUEST]: async ({commit}) => {
    await axios.post('auth/register',)
      .then(response => {
        commit(AUTH_SUCCESS, response);
      })
      .catch(error => {
        console.log(error);
      });
  },
};

const mutations = {
  [AUTH_SUCCESS]: (state, resp) => {
    state.token = resp.data.token;
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}

当尝试从store/index 获取商店时,它返回undefined。 可能在 store 初始化之前已经调用了 axios。

但是我该如何处理呢?

应用程序的流程是。

user register->get token->update store with this token->add to the axios header.

所以现在,所有对 api 的调用都将提供令牌。

【问题讨论】:

  • 我怀疑问题出在 auth 模块上。当发出 axios 请求时,store 将已经初始化。您是否在 store 对象或 store.getters.auth.token 上未定义?
  • @AllkinI 在 store.getters.auth.token 上未定义
  • @Allkin 使用 auth 模块编辑了我的问题

标签: vue.js axios vuex


【解决方案1】:

首先,您应该小心Vue's reactivity caveats,它也会影响 Vuex。在您的情况下,您是在突变中的对象内添加一个新属性。

回到主要问题,您的 axios.js 文件在 Store 实例构建之前正在执行,这就是为什么您无法访问它并且您得到未定义的原因。

我要做的是:

axios.js

import axios from 'axios';
const API_URL = process.env.API_URL;

export default (store) => axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${store.getters.auth.token}`
  }
});

然后在你的主文件中,你有主要的 Vue 实例化,我只是在那里运行函数,导出该函数的返回。

【讨论】:

  • 您好,感谢您的帮助。按照你的方式,我仍然认为商店是未定义的。
猜你喜欢
  • 2017-08-18
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 2013-01-15
相关资源
最近更新 更多