ES6封装Axios和使用

封装axios,使用了ES6语法

import axios from 'axios'

class XHR {
  constructor(config) {
    this.config = {
      // baseURL: 'https://www.fastmock.site/mock/c17a53c1e9a5235f42f6af1f21fab7c2/traffic', // mock接口
      baseURL: 'https://bc.yncgj.cn:10009//bcz/api/',	// 线上服务器地址
      // baseURL: 'http://192.168.2.49:10920/bcz/api/',		// 本地调试地址
      headers: {},
      crossDomain: true
    }
    // 初始化 请求实例
    this.config = Object.assign(this.config, config)
    this.$request = axios.create(this.config);
    //请求拦截器
    this.$request.interceptors.request.use(
      config => {
        config.withCredentials = false;
        // console.log(sessionStorage.getItem('toKen'));
        if (sessionStorage.getItem('toKen')) {
          config.headers.Authorization = sessionStorage.getItem('toKen') + '';
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      });
  }

  get(url, data) {
    return this.request(url, data, 'GET')
  }

  post(url, data, config = {}) {
    return this.request(url, data, 'POST', config)
  }

  request(url, data, method = 'GET', option) {
    // debugger
    // 格式化参数
    if (typeof data === 'string') {
      method = data
      data = {}
    }
    const config = {
      url,
      method
    }
    // 区分 post get
    if (method === 'GET') {
      config.params = data
      config.data = qs.stringify(data)
    } else {
      config.data = data
    }
    // 发起请求
    return this.$request(config).then(({
      data
    }) => {
      const result = {
        code: parseInt(data.code || 0),
        count: parseInt(data.count || 0),
        data: data.data,
        msg: data.message,
      }
      return result
    }).catch((error) => {
      error = error && error.toString()
      console.error('接口调用异常: error', error)
      if (error && (error.includes('Error:') || error.includes('<html'))) {
        error = '接口异常,请联系管理员!'
      }
      return Promise.reject(error)
    })
  }
}

export default XHR

封装接口

import XHR from './xhr'
const req = new XHR()

export default {
  /**
   * 登录
   */
  signIn: params => req.get(`/toLogin`, params),
  /**
   * 设施大类
   */
  equipment: params => req.get(`/facilityType/queryFacilityTypeParentList`, params),
  /**
    * 提交表单
    */
  submitForm: params => req.post(`/facility/save`, params),
  /**
    * 上传
    */
  upLoad: params => req.post(`/facility/uploadBatch`, params),
}

挂在到全局,mian.js中

import allRequertAjax from "./API/interface";
Vue.prototype.$http = allRequertAjax;

使用

        async getEquipment() {
            try {
                const { data } = await this.$http.equipment();
                this.list = data;
            } catch(error) {}
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值