axios的二次封裝

在項(xiàng)目下新建一個(gè)service文件夾(與package.json同級(jí)),子文件:http.js 對(duì)axios請(qǐng)求頭、攔截器等, reset.js:請(qǐng)求方法的封裝,get,post等。
axios的二次封裝跟api的封裝、或者在vuex的store中使用,
axios的reset用于api封裝用,提供api封裝中使用,以及store中使用。

1.http.js,axios請(qǐng)求頭、攔截器等,

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'

// 創(chuàng)建axios實(shí)例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // 請(qǐng)求超時(shí)時(shí)間
})

// request攔截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken() // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 攔截器
service.interceptors.response.use(
  response => {
    /**
     * code為非20000是拋錯(cuò) 可結(jié)合自己業(yè)務(wù)進(jìn)行修改
     */
    const res = response.data
    const codeReg = /^20\d+/
    if (!codeReg.test(response.status)) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      // 50008:非法的token; 50012:其他客戶端登錄了;  50014:Token 過期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm(
          '你已被登出,可以取消繼續(xù)留在該頁(yè)面,或者重新登錄',
          '確定登出',
          {
            confirmButtonText: '重新登錄',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 為了重新實(shí)例化vue-router對(duì)象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

2、reset.js,請(qǐng)求方法的封裝,get,post等

import http from './http.js'

export default {
  post(url, data, config) {
    return http.post(url, data, config)
  },

  get(url, params, config) {
    const getConfig = {}
    if (params) {
      Object.assign(getConfig, {
        params
      })
    }
    if (config) Object.assign(getConfig, config)

    return http.get(url, getConfig)
  },

  put(url, data, config) {
    return http.put(url, data, config)
  },

  delete(url, params, config) {
    const delConfig = {}
    if (params) {
      Object.assign(delConfig, {
        params
      })
    }
    if (config) Object.assign(delConfig, config)

    return http.delete(url, delConfig)
  }
}

3.api封裝使用:

src/api/template.js:
 import request from '@/service/http.js' // axios的封裝 后續(xù)添加axios二次封裝

//  /cosmopaas-dev為跨域規(guī)則 前面文章有提到
// post方式傳參用data
export function getCommonList(query) {
  return request({
    url: '/cosmopaas-dev/algorithm/getAlgorithmModelPage',
    method: 'post',
    data: query
  })
}

4.store中使用:

//在store的xxx.js中引入
import api from '@/service/reset.js'

export default {
  state: {
    tenants: [], // all tenants
  },
  getters: {
    tenants: state => state.tenants, //  all tenants
    clusters: state => state.clusters //  all clusters
  },
  mutations: {
    alertTenants: (state, data) => { // all tenants
      state.tenants = data
    },
    alertClusters: (state, data) => { // all tenants
      state.clusters = data
    }
  },
  actions: {
    // get all tenants
    getTenantsAPI: (context) => {
      api.get('/api/dce/tenants').then( res => {
        console.log(res.data)
        context.commit('alertTenants', res.data)
      }).catch( error => {
        console.log(error)
      })
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容