在这里插入图片描述

第一步:

建立cookie的 添加、设置、和删除

auth.js

import Cookies from 'js-cookie'

const TokenKey = 'APPMGRID'  //APPMGRID这个token名字自己定义

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

第二步:

点击登录按钮的时候 去调用登录接口

 this.$store.dispatch('user/login', this.loginForm).then(data => {
     this.loading = false
      if (data === null) return
      this.$router.push({ path: '/dashboard' })
    }).catch(() => {
      this.loading = false
    })

this.loginForm 是调用登录传递的数据。


第三步:

设置store,login 登录的API和操作cookie的方法。调用login接口的时候,获取token信息,然后设计进 cookie。
store

import { login } from '@user.js' //引入user.js 
import { getToken, setToken, removeToken } from '@auth.js'   //引入auth.js

const state = {
  token: getToken()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(response => {
          const { APPMGRID } = response
          commit('SET_TOKEN', APPMGRID)
          setToken(APPMGRID)
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

接口API地址

user.js

export function login(data) {
  return request({
    url: '/home/login',
    method: 'post',
    data
  })
}

第四步:

封装的请求文件

request.js

import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (config.method === 'post') {
      config.data = qs.stringify(config.data)
    }
    if (config.method === 'get') {
      config.url = config.url + '?' + qs.stringify(config.data)
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      if (getToken()) {
        config.headers['APPMGRID'] = getToken()
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const data = response.data
    if (data.result === 'success') {
      return Promise.resolve(data.data)
    } else {
      MessageBox.alert(data.message + ': ' + data.detail, '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        lockScroll: false
      }).catch(() => {})
      return null
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

设置成功以后每次请求都会 头部 家伙加上数据:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐