axiosグローバル設定とローカルインスタンス化設定の使用


一、グローバルhttpリクエストのカプセル化
1、パッケージ
/**
* @Author: 
* @Date: 2019/10/14
* @Description:   http  
* @remarks:
*/

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
let lock = false //                   

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20 * 1000 // request timeout
})

/**
 *      
 *             config
 * config             
 *      axios        ,                   
 *                      
 *                 
 */
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

/**
 *      
 *                    
 *             403       
 *            403 ,       :          
 */
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0 && res.code !== 5001) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (!lock) {
        // 29999:   token;  30000: Token   ;
        if (res.code === 29999) {
          lock = true
          // to re-login
          MessageBox.confirm('     ,   。', '    ', {
            confirmButtonText: '  ',
            cancelButtonText: '  ',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
        if (res.code === 30000) {
          lock = true
          // to re-login
          MessageBox.confirm('       ,       。', '    ', {
            confirmButtonText: '  ',
            cancelButtonText: '  ',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (!lock) {
      // 29999:   token;  30000: Token   ;
      if (error.response.data.code === 29999) {
        lock = true
        // to re-login
        MessageBox.confirm('     ,   。', '    ', {
          confirmButtonText: '  ',
          cancelButtonText: '  ',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      if (error.response.data.code === 30000) {
        lock = true
        // to re-login
        MessageBox.confirm('       ,       。', '    ', {
          confirmButtonText: '  ',
          cancelButtonText: '  ',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service

2、使用
import request from '@/utils/request'
export function queryStatus(data) {
  return request({
    url: 'api/cr/chapter/queryStatus',
    method: 'post',
    data
  })
}

二、ローカルインスタンス化と使用
シーンを使用:
ローカルaxiosインスタンス化を使用するのは、httpのグローバルインスタンス化要求にグローバルな応答ブロックコードがあるためです.一部のインタフェースでステータスコードcodeを返すことができない場合、responseを得ることができません.この場合、現在のapiでaxiosを再インスタンス化し、新しい応答ブロックコードを設定するか、関連業務を行うために設定しない必要があります.
/**
* @Author: 
* @Date: 2019/11/09
* @Description:       
* @remarks:
*/

import request from '@/utils/request'
import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  timeout: 20 * 1000 // request timeout
})

service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken()
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

/**
 *      
 *                    
 *             403       
 *            403 ,       :          
 */
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // const res = response.data
    return response
  },
  error => {
    // 29999:   token;  30000: Token   ;
    if (error.response.data.code === 29999) {
      // to re-login
      MessageBox.confirm('     ,   。', '    ', {
        confirmButtonText: '  ',
        cancelButtonText: '  ',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }
    if (error.response.data.code === 30000) {
      // to re-login
      MessageBox.confirm('       ,       。', '    ', {
        confirmButtonText: '  ',
        cancelButtonText: '  ',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }
    return Promise.reject(error)
  }
)

//   Excel    
export function exportExcelModel(data) {
  var url = process.env.VUE_APP_BASE_API + '/system/model/downloadModel?code=' + data.code
  return service({
    url,
    method: 'get',
    responseType: 'blob',
    data
  })
}