axios请求API封装

学习分享2年前 (2022)更新 bestcyt
895 0 0

这样做的好处,

可以统一管理接口文件,多人开发分功能模块管理接口文件,低代码量,易懂易用方便快捷。

api.js

import axios from './interceptor.js'
import aaaa'./aaaa'
import formApi from './form'

const reqUrl = 'https://xxxxxx'

const apiObj = {

  getEncryption: function(url, data) {
    return axios({
      method: 'get',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      params: data,
      data: data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },

  get: function(url, data) {
    return axios({
      method: 'get',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      params: data,
      data: data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },

  post: function(url, data = {}) {
    return axios({
      method: 'post',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      data: data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },
  postFile: function(url, data) {
    return axios({
      method: 'post',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      data: data,
      cache: false,
      processData: false,
      contentType: false,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },

  postUrl: function(url, set) {
    return axios({
      method: 'post',
      url: reqUrl + url + '?' + set.type + '=' + set.data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },
  postParam: function(url, data) {
    return axios({
      method: 'post',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      params: data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },
  delete: function(url, data) {
    return axios({
      method: 'delete',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      params: data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  },
  getForm: function(url, data) {
    return axios({
      method: 'post',
      url: url.indexOf('http') !== -1 ? url : reqUrl + url,
      params: data,
      data: data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    })
  }

}

const api = Object.assign({}, apiObj, aaaa,  formApi)
export default api

表单页面接口文件:form.js

export default {
  getApply(data) {
    return this.get('/xxxx', {})
  },
  getLanguage(data) {
    return this.post('/xxxxxx', data)
  },
}

main.js 全局挂载:


import api from './api/api.js'


Vue.prototype.$api = api

页面使用:

getApply() {
   this.$api.getApply().then(res => {
      if (res.success) {
          this.ruleForm.c = res.data
      }
   }).catch((err)=>{
      console.log('err---',err)
   });
},
© 版权声明

相关文章