Axios 的简单封装

参考 axios 官方文档

src/libs/ajaxRequest.js

import axios from 'axios'
// import qs from 'qs'
import router from '@/router'
import store from '@/store'

class ajaxRequest {
  constructor() {
    this.baseURL =
      process.env.NODE_ENV === 'production'
        ? 'http://xxx:8081/tob/back'
        : '/back'
    this.timeout = 5000
  }

  merge(options) {
    return {
      ...options,
      baseURL: this.baseURL,
      timeout: this.timeout
    }
  }

  // 拦截器
  setInterceptor(instance) {
    instance.interceptors.request.use(
      req => {
        req.headers.Authorization = localStorage.getItem('token')
        if (req.method === 'get') {
          req.headers = {
            token: localStorage.getItem('token'),
            user_id: localStorage.getItem('id')
          }
        } else if (req.method === 'post') {
          req.data = {
            ...req.data
          }
          req.headers = {
            token: localStorage.getItem('token'),
            user_id: localStorage.getItem('id')
          }
        }
        return req
      },
      err => {
        console.log('req:', err)
        return Promise.reject(err)
      }
    )
    instance.interceptors.response.use(
      res => {
        let token = res.headers.authorization
        if (token) {
          // 如果 header 中存在 token,那么触发 refreshToken 方法,替换本地的 token
          axios.defaults.headers.common['Authorization'] = token
        }
        // 判断用户登录状态
        if (
          res.data.result_msg === 'No login' ||
          res.data.result_code === '400' ||
          res.data.result_msg === 'Timeout'
        ) {
          // 如果没有登录
          // 清除 token & 用户信息
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          // 跳转到登录页
          if (window.location.pathname !== '/') {
            router.replace({
              path: '/'
            })
          }
        }

        // 根据返回的错误信息,触发 Vuex 状态管理
        // if (res.data.result_code == 400) {
        //   let obj = {
        //     flag: true,
        //     errorMsg: res.data.result_msg
        //   }
        //   store.commit('TipsBar', obj)
        // }
        return res
      },
      err => {
        console.log('req:', err)
        return Promise.reject(err)
      }
    )
  }

  request(options) {
    let instance = axios.create()
    let config = this.merge(options)
    this.setInterceptor(instance) // 拦截器
    return instance(config)
  }
}

const $axios = new ajaxRequest()

// 导出 get 方法
export const get = async (url, params) => {
  try {
    return await $axios.request({
      method: 'get',
      url,
      params
    })
  } catch (error) {
    console.log(error)
  }
}

// 导出 post 方法
export const post = async (url, data) => {
  try {
    return await $axios.request({
      method: 'post',
      url,
      data
    })
  } catch (error) {
    console.log(error)
  }
}

src/api/post.js

import { post } from '../libs/ajaxRequest'
import md5 from 'js-md5'

// post demo
export const postLogin = obj => {
  let data = {
    username: obj.username,
    password: md5(obj.password)
  }
  return post('post-url', data)
}

src/api/get.js

import { get } from '../libs/ajaxRequest'

// get demo
export const getList = (pageNo, key) => {
  let params = {
    pageNo
  }
  // key 为可选参数,如:搜索关键词
  key && (params.key = key)
  return get('get-url', params)
}

组件中使用

import { getList } from '../api/get'
import { postLogin } from '../api/post'

export default {
  data() {
    return {
      list: []
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      // 可以直接 await,因为在 ajaxRequest.js 已经 try...catch 了
      try {
        let result = await getList(1)
        this.list = result
        console.log(this.list)
      } catch (error) {
        console.log(error)
      }
    },
    async postData() {
      let userInfo = {
        username,
        password
      }
      // 可以直接 await,因为在 ajaxRequest.js 已经 try...catch 了
      try {
        let result = await postLogin(userInfo)
        console.log(result)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
Last Updated: 7/8/2019, 3:36:58 PM