//1、登录得到token
up() {
      this.none = true;
      let _this = this;
      if (!_this.valueItem.username || !_this.valueItem.password) {
        return "";
      } else {
        let data = {
          username: _this.valueItem.username,
          password: _this.valueItem.password,
        };
        ajaxHttp
          .readyLogin(data)
          .then((res) => {
            console.log(res);
             _this.changeLogin({ Authorization: res.data.token });
            sessionStorage.setItem("userToken", res.data.token);
            this.$router.push({ path: "/" });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
//store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store ({
    state: { 
        // 存储token
      Authorization: sessionStorage.getItem('Authorization') ? sessionStorage.getItem('Authorization') : ''  
    },
    mutations: {
       // 修改token,并将token存入localStorage
      changeLogin (state, user) {
        state.Authorization = user.Authorization;
        sessionStorage.setItem('Authorization', user.Authorization);
      }
    }
})

 

//3、http.js
//在请求头中添加token

const service = axios.create({
  baseURL: base_url, // api的base_url
  timeout: 5000 // request timeout
})


// request interceptor
service.interceptors.request.use(config => {
  // 判断是否存在token,如果存在的话,则每个http header都加上token
  let token = sessionStorage.getItem('Authorization')
  if (!config.headers.hasOwnProperty('Authorization') && token) {
    config.headers.Authorization = token;
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

 

Logo

前往低代码交流专区

更多推荐