对axios的二次封装

这个封装也是在别人的基础上进行的封装

原博在这里vue实力封装axios

因此非常感谢这位同学

个人感觉这个封装已经比较到位了,支持常用的get以及post,post可以选择是用键值对key-value或者是json格式进行传输数据,注意post选择用键值对不用在自己设置contentType!

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

 就是上面这个,因为如果你用qs将数据序列化之后,axios会自动加上contentType,如果你自己再加上contentType,参数不会出现你想要的键值对形式,会变成类似于id=1&name=zhangsan的形式

注意事项:

  1. 需要引用element-ui以及qs
  2. 传递的参数为(url,data,config),data根据需求是否需要传递vue的实例对象this,config里有stringify的配置项,config: {stringify: true} 需要序列化data 默认,config: {stringify: false} 以json格式传输参数
  3. 前后端交互的基础json格式为
    {
      "code": 20000,
      "data": null,
      "message": null
    }

    在这里进行了一个统一的拦截,如果后端传递的code为41000,即为未授权请求,前端将把路由导航到/login登录页面,这个需要在传递参数时就将vue的实例对象this传递过来才能实现

import axios from 'axios'
import ElementUI from 'element-ui'
import Vue from 'vue'
import qs from 'qs'

let axiosIns = axios.create({
  withCredentials: true,
  baseURL: process.env.BASE_API // api 的 base_url
});

axiosIns.interceptors.response.use(function (response) {
  let status = response.status;
  if (status === 200) {
    if (response.data.code !== 20000) {
      return Promise.reject(response)
    }
    return Promise.resolve(response);
  } else {
    return Promise.reject(response);
  }
});

let ajaxMethod = ['get', 'post'];
let api = {};
ajaxMethod.forEach((method) => {
  // config: {stringify: true} 需要序列化data 默认
  // config: {stringify: false} 以json格式传输参数
  api[method] = function (url, data, config = {stringify: true}) {
    return new Promise(function (resolve, reject) {
      if (method === 'post') {
        axiosIns.request({
          url: url,
          method: 'post',
          data: config.stringify && data ? qs.stringify(data) : data
        }).then((response) => {
          resolve(response);
        }).catch((response) => {
          reject(response)
          // 检查服务器是否存在该MD5值
          if (response.data.code !== 20033 && response.data.code !== 20034) {
            ElementUI.Notification.error({
              title: 'error',
              message: response.status === 200 ? response.data.msg : `网络错误`,
              duration: 2000
            })
          }
          // 如果从后台传来的code未41000(未授权、未登录)sessionStorage移除user对象,页面刷新
          if (response.data.code && response.data.code === 41000) {
            window.setTimeout(() => {
              sessionStorage.removeItem('user');
              location.reload();
            }, 2000);
          }
        })
      } else if (method === 'get') {
        axiosIns.request({
          url: url,
          method: 'get',
          params: {
            ...data
          }
        }).then((response) => {
          resolve(response);
        }).catch((response) => {
          reject(response)
          // 检查服务器是否存在该MD5值
          if (response.data.code !== 20033 && response.data.code !== 20034) {
            ElementUI.Notification.error({
              title: 'error',
              message: response.status === 200 ? response.data.msg : `网络错误`,
              duration: 2000
            })
          }
          // 如果从后台传来的code未41000(未授权、未登录)sessionStorage移除user对象,页面刷新
          if (response.data.code && response.data.code === 41000) {
            window.setTimeout(() => {
              sessionStorage.removeItem('user');
              location.reload();
            }, 2000);
          }
        })
      }
    })
  }
});

Vue.prototype.$axios = api;

const post = api['post']
const get = api['get']
export {
  post,
  get
}

调用方式:

  1. 可以直接用vue的实例对象this.$axios.get或者this.$axios.post进行调用
  2. import{get,post}

以上为全部内容,个人水平有限,如有问题,欢迎指正,谢谢!

你可能感兴趣的:(前端,vue)