欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

三、VUE项目BaseCms系列文章:axios 的封装

程序员文章站 2023-11-21 22:02:52
项目开发中 ajax 是不可缺少的,一个好的封装可以减少我们很多的重复代码,维护也更方便。在 vue 开发中我们用的比较多的就是 axios。下面代码是项目中用到的 axios 的封装。 http.js 注: 1. 上面代码依赖了 elementui 框架的 Message 组建,用于提示错误消息 ......

项目开发中 ajax 是不可缺少的,一个好的封装可以减少我们很多的重复代码,维护也更方便。在 vue 开发中我们用的比较多的就是 axios。下面代码是项目中用到的 axios 的封装。

http.js

/**
 * 描述: axios封装,方便使用
 */

import axios from 'axios'
import router from '../router'
import { message } from 'element-ui'

// 提示
const tip = msg => message.error(msg)

// 跳转到登录页
const tologin = () => {
  router.replace({
    path: '/login',
    query: { redirect: router.currentroute.fullpath }
  })
}

// 错误统一处理
const errorhandle = (status, other) => {
  switch (status) {
    // 未授权,请登陆
    case 401:
      tologin()
      break

    // 登录过期,清除token,跳转到登录页
    case 403:
      tip('登录过期,请重新登录!')
      localstorage.removeitem('token')
      settimeout(() => { tologin() }, 1000)
      break

    // 未找到资源
    case 404:
      tip('请求的资源不存在!')
      break

    // 其他状态码
    default:
      console.log(other)
  }
}

// 实例对象
let instance = axios.create({
  timeout: 6000,
  headers: { 'content-type': 'application/json' }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 登录流程控制中,根据本地是否存在token判断用户的登录情况
    // 但是即使token存在,也有可能token是过期的,所以在每次的请求头中携带token
    // 后台根据携带的token判断用户的登录情况,并返回给我们对应的状态码
    // 而后我们可以在响应拦截器中,根据状态码进行一些统一的操作。
    const token = localstorage.getitem('token')
    token && (config.headers.authorization = token)
    return config
  },
  error => promise.error(error)
)

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  res => {
    if (res.data.code === 200) {
      return promise.resolve(res)
    } else {
      tip(res.data.message)
      return promise.reject(res)
    }
  },

  // 请求失败
  error => {
    const { response } = error
    if (response) {
      // 请求已发出,但状态码不在 2xx 的范围
      errorhandle(response.status, response.data.message)
      return promise.reject(response)
    } else {
      tip('请求未响应,超时或断网!')
      return promise.reject(error)
    }
  }
)

export default instance

 

注:

1. 上面代码依赖了 elementui 框架的 message 组建,用于提示错误消息

2. 之所以没有为 实例对象 instance 配置 baseurl,是为了防止有多个不同服务的情况。