封装axios接口

封装axios接口作用:
1.统一对请求参数拼接URL
2.统一管理token
3.统一处理网络http错误
4.统一处理程序逻辑错误,业务中自定义code = 200才认为业务成功;

import Vue from 'vue'
import axios from 'axios'
import { Message} from "element-ui";
import store from '../store/index'
import storageMethod from './validate'
import router from "../router";


const http = axios.create({

})

/*
* 请求拦截
* */
http.interceptors.request.use(config => {
    //在请求发出之前进行一些操作,比如请求头携带内容   
   
    //  封装的GetSessionToken的this指向不同 所以不能使用封装的函数
    // 判断TOKEN有误失效,若失效的话,需要在响应拦截中更新token
    config.headers['Authorization'] =  storageMethod.GetSessionToken();  
    return config;
}, err => {
    return Promise.reject(err);
});
/**
 * 响应拦截
 */
http.interceptors.response.use(response=> {
    if (response.status && response.status == 200 && response.data.status == 'error') {
        store.state.variable.passWordError = false
        return;
    }
    return response;
}, err=> {
    
    switch (err && err.response && err.response.status) {
        case 400:
            err.message = '请求错误'
          break
        case 401:
            {
                err.message = '未授权,请登录'
                console.log(err.response)
                Message.error({message: err.response.data.msg})
                storageMethod.DeleteTokenCookie()
                router.push({name:'login'})
           }           
          break
        case 403:
            err.message = '拒绝访问'
          break
        case 404:
            err.message = '未找到访问地址'
          router.push({name: '404'})
          break
        case 408:
            err.message = '请求超时'
          break
        case 426:
            {
                store.state.variable.passWordError = true
                if (!store.state.variable.passWordError) {
                    Message.error({message: '密码错误!'});
                }
            }            
            break;
        case 500:
            err.message = '服务器内部错误'
          break
        case 501:
            err.message = '服务未实现'
          break
        case 502:
            err.message = '网关错误'
          break
        case 503:
            err.message = '服务不可用'
          break
        case 504:
            err.message = '网关超时'
          router.push({name: '404'})
          break
        case 505:
            err.message = 'HTTP版本不受支持'
          break
        default:
            {
                console.log(err)
            }
      }

    // return Promise.resolve(err);
    return Promise.reject(err);
})
/**
 * 请求地址处理
 * @param {*} actionName action 路径名称
 */
http.prefixUrl = (actionName) => {     
    if(store.state.variable.falg) {
        // 适用于六盘山项目中有内外网分隔的情况,访问后台的接口与访问web服务的接口IP一致(外网Ip)
        return "http://"+window.location.host + actionName
    }else {
        return (process.env.NODE_ENV !== 'production' ? process.env.VUE_APP_development_URL : process.env.VUE_APP_production_URL ) + actionName
    }
}

/*
*  登录请求
* */
http.loginRequest = (url,parameter) => {    
    return  new Promise((resolve,reject) => {
        http({
            method:'post',
            url: http.prefixUrl(url),
            params:parameter
        }).then(res => {
            resolve(res);
        }).catch(err => {
            console.log(err)
            reject(err)
        })
    })
}




 /** api文档自动生成模板
    * @url {newOnePromise} /axios/:id Request User information
    * @apiName newOnePromise
    * @apiGroup sendAxios
    *
    * @apiParam {opts} is a json object ,like 
    * {type:'post',url:'',data:null,headers:null , success: function (data) {} ,error:function (data) {} ,noError:false,errorMsg:'业务模块' }
    *  type is one of { 'post','get','put','delete','options','patch'}
    *  url is url
    * 
    * onePromise({
    *    url: "basicCore/xxx",
    *   type: "post",
    *   timeout:30000,
    *   contentType: "application/json",        
    *   data: "iconId=" + iconId,
    *    success: function (data) {
    *        //接口成功的业务代码
    *       返回数组,  数组长度是data.length ,按索引访问数组数据 data[i]                
    *    },
    *   error: function (XMLHttpRequest, textStatus, errorThrown) {
    *        //alert("服务出错:" + XMLHttpRequest.statusText + ",代码 " + XMLHttpRequest.status);
    *    },
    *   noError :true , //提示错误信息
    *    errorMsg:'某业务模块'
    * });

    *调取示例:
    * this.$sendAxios.onePromise(
    *      {
    *          type:'post',
    *          url:'/permit/role/list',
    *          data:this.form,
    *          success: function (res) {  // 此处对应响应数据中的data.data                  
    *             console.log('success  -- '+ JSON.stringify(res) )
    *           },
    *          error: function (res) {                 
    *            console.log('error  -- '+JSON.stringify(res))
    *          },
    *           noError :false , //提示错误信息
    *           errorMsg:'某业务模块YYY'       
    *      })
    *
    *  或者
    *
    *  this.$sendAxios.onePromise(
    *      {
    *          type:'post',
    *          url:'/permit/role/list',
    *          data:this.form
    *      })then((data) => {}
    *
    * @apiSuccess
    * @apiSuccess
    */

   http.onePromise = (opts) => {  
    return new Promise((resolve,reject) => {
        http({
            method:opts.type || "post",
            url: http.prefixUrl(opts.url),
            timeout: opts.timeout || 30000,
            data:(opts.data)||(null),
            headers:(opts.headers)||({'Content-Type':'application/json;charset=UTF-8'}),           
        }).then(res => {
            if (res.status == "200" ) { 
                if(res.data.code == "200") { //只有接口成功返回且后台接口处理返回码为200时才认为成功 
                    if (opts.success) {
                        opts.success(res.data);
                    }
                } else {
                    if (!opts.noError) {
                        console.error( opts.errorMsg || (" 服务访问出错(" + res.data.code + "):" + res.data.message))
                    };
                    if (opts.error) {                
                        opts.error(res.data);
                    }
                }
            }
            resolve(res);//执行成功访问
        }).catch(err => {
            
            if (!opts.noError) {
                console.error( opts.errorMsg || (" 服务访问出错(" + err.status + "):" + err.responseText))
            };
            if (opts.error) {                
                opts.error(err);
            }
             reject(err) //接口执行失败访问
        }).finally(res =>{
            //
        })
    })

};



export default http ;


你可能感兴趣的:(封装axios接口)