如何在Vue JS中添加标头以获取请求?

时间:2019-08-04 13:23:37

标签: vue.js axios vuex

我正在从api获取数据,登录后如何发送带有令牌的get请求?

它显示错误createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 401

export default new Vuex.Store({
  state: {
    users: []
  },
  mutations: {
    setUsers(state, args){
      state.users = args;
    }
  },
  actions: {
    login({ }, arg) {
      axios.post('login/', { username: arg.username, password: arg.password })

        .then((response) => {
          console.log(response);
          let accessToken = response.token.data;
          localStorage.setItem('token', accessToken);
          localStorage.setItem('user', response.data.user);
          axios.defaults.headers.common['Authorization'] = accessToken;
          window.isSignedIn = true;
          router.push('/');
        })

        .catch((error) => {
          console.log(error);
        })
    },
    getUsers({ commit }){
      let { data } = axios.get('v1/user/list/');
      commit('setUsers', data);
    }
  }
})

1 个答案:

答案 0 :(得分:1)

取决于您使用的身份验证。尝试: axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;

其他HTTP authentication schemes