美文网首页
Axios拦截器

Axios拦截器

作者: Eden0204 | 来源:发表于2021-05-31 20:47 被阅读0次
    import axios from 'axios'
    import ConfigBase from '@/config/index'
    import { Message } from 'element-ui'
    import { loading } from '@/components/index.js'
    import { toLogout } from './app'
    import api from '@/apis'
    
    const to = promise => {
      return promise.then(data => [data, null]).catch(err => [undefined, err])
    }
    /**
     * 创建 axios 实例
     */
    const service = axios.create({
      timeout: 15000, // // 超时时间
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    })
    service.interceptors.request.use(
      (config) => {
        const {
          method = 'POST',
          showLoading = true,
          data = {},
          isDiagnosis = false
        } = config
        // 没有特殊配置,则自动显示加载中loading
        if (showLoading) {
          // 放个统一的loading
          loading(true)
        }
        config.data = method === 'post' ? data : ''
        config.params = method === 'get' ? data : ''
        // 是否诊疗路劲接口
        data.visitSiteId = isDiagnosis ? ConfigBase.visitSiteIdZllj : ConfigBase.visitSiteId
        if (isDiagnosis) {
          config.headers.apiToken = localStorage.getItem('apiToken')
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
    service.interceptors.response.use(
      (response) => {
        const { codeHandle = {}} = response.config
        const res = response.data
        loading(false)
        if (res.error) {
          return Promise.reject(res)
        }
        const code = res.code
        const isSuccess = code === 0 || code === '0' || code === '000000'
    
        if (isSuccess) {
          return Promise.resolve(res.data || res.result)
        } else if (codeHandle === 'skip') { // 允许所有异常code通过
          return Promise.reject(res)
        } else if (codeHandle === 'silent') { // 所有状态码静默
          console.error(`[request] 已配置所有异常静默 ${code}: ${res.message}`)
          return Promise.reject(res)
        } else if (code === '1008') {
          Message.error(res.message || res.data.message || '网络超时,请重新登录')
          toLogout()
        } else {
          Message.error(res.message || res.data.message || '网络异常')
          return Promise.reject(res)
        }
      },
      (error) => {
        loading(false)
        Message.error('网络异常')
        return Promise.reject(error)
      }
    )
    /** aa
     * @params url(请求接口地址)
     * @params data(请求参数)
     * @params ops(请求附加参数)
     */
    export const postAsync = (url, options = {}) => {
      options.method = 'POST'
      options.url = url
      return to(service(options))
    }
    
    /** aa
     * @params url(请求接口地址)
     * @params data(请求参数)
     * @params ops(请求附加参数)
     */
    export const getAsync = (url, options = {}) => {
      options.method = 'GET'
      options.url = url
      return to(service(options))
    }
    
    /**
     * @params url(请求接口地址)
     * @params data(请求参数)
     * @params ops(请求附加参数)
     */
    export const get = (url, options = {}) => {
      options.method = 'GET'
      options.url = url
      return service(options)
    }
    
    /**
     * @params url(请求接口地址)
     * @params data(请求参数)
     * @params ops(请求附加参数)
     */
    
    export const post = (url, options = {}) => {
      options.method = 'POST'
      options.url = url
      return service(options)
    }
    
    export default {
      install(_Vue) {
        _Vue.prototype.$api = api
        _Vue.prototype.$postAsync = postAsync
        _Vue.prototype.$getAsync = getAsync
        _Vue.prototype.$getRawFetch = get
        _Vue.prototype.$postRawFetch = post
      }
    }
    
    

    dd config

    import { request } from './request';
    import { commonNotify } from './utils.js';
    import { errorMessage } from './error';
    import storage from './localStorage';
    
    export const to = promise =>
      promise.then(data => [data, null]).catch(err => [undefined, err]);
    
    /**
     * http请求 controller 会拦截api 并根据ddHost赋值实际对应
     * @param {*} type post get
     * @param {*} url api
     * @param {*} params 数据
     * @param {*} config ddHost请求的其他服务代理字段 silence=skip静默处理 loading暂时没添加全局loading
     * @returns
     */
    export async function fetch(
      type = 'post',
      url,
      params = {},
      config = { ddHost: '', silence: '', loading: false },
    ) {
      const { ddHost = '', silence = '', loading = false } = config;
      if (ddHost) {
        params.ddHost = ddHost;
      }
      // 获取当前接口权限列表
      const roleInfo = storage.get('roleInfo') || {};
      const { permission_list = [] } = roleInfo || {};
    
      if (
        !permission_list ||
        !Array.isArray(permission_list) ||
        !permission_list.includes(url)
      ) {
        return Promise.reject(`无当前接口${url}权限`);
      }
      const [{ data }, err] = await to(request(type, { url, params }));
      if (err) {
        return Promise.reject(err);
      }
    
      const { status_code } = data || {};
      // 请求成功的状态码
      const isSuccessCode = [0, '0'].includes(status_code);
      if (isSuccessCode) {
        // 请求成功
        return Promise.resolve(data.data);
      } else if (!isSuccessCode && silence === 'skip') {
        // 静默处理:特殊情况不处理的异常状态码
        return Promise.resolve(data);
      }
    
      // 错误code提示,并抛异常
      commonNotify(window.vm, {
        type: 'error',
        message: errorMessage[status_code] || '接口异常',
      });
      return Promise.reject('接口异常');
    }
    
    /**
     * post请求,经过to方法处理
     * @param {*} url
     * @param {*} params
     * @param {*} config
     * @returns
     */
    export function fetchPost(url, params = {}, config = {}) {
      return to(fetch('post', url, params, config));
    }
    
    /**
     * get请求,经过to方法处理
     * @export
     * @param {*} url
     * @param {*} [params={}]
     * @param {*} [config={}]
     * @return {*}
     */
    export function fetchGet(url, params = {}, config = {}) {
      return to(fetch('get', url, params, config));
    }
    
    /**
     * post请求 Promise().then().catch()形式的写法、以及用于Promise.all()
     * @param {*} url
     * @param {*} params
     * @param {*} config
     * @returns
     */
    export function rawFetchPost(url, params = {}, config = {}) {
      return fetch('post', url, params, config);
    }
    
    /**
     * get请求 Promise().then().catch()形式的写法、以及用于Promise.all()
     * @param {*} url
     * @param {*} params
     * @param {*} config
     * @returns
     */
    export function rawFetch(url, params = {}, config = {}) {
      return fetch('get', url, params, config);
    }
    
    export default {
      install(_Vue) {
        _Vue.prototype.$fetchPost = fetchPost;
        _Vue.prototype.$fetchGet = fetchGet;
        _Vue.prototype.$rawFetch = rawFetch;
        _Vue.prototype.$rawFetchPost = rawFetchPost;
      },
    };
    
    

    相关文章

      网友评论

          本文标题:Axios拦截器

          本文链接:https://www.haomeiwen.com/subject/fdtisltx.html