1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
* 说明:axios 二次封装 * 参数:type //请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 * apiName //接口地址 * url //接口模块 * options //配置参数,例如传{params={}} */
import axios from 'axios' import api from 'service/apiConfig' //真实接口配置 import store from 'vuexStore/store.js' //引用vuex import qs from 'qs' import template from 'url-template'
/** axios基础配置 */ axios.defaults.timeout = 5000; axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
// http request 拦截器 // 一般设置 token axios.interceptors.request.use( config => { if (localStorage.aynUserToken) { config.headers.common['X-AIYANGNIU-SIGNATURE'] = localStorage.aynUserToken; } return config; }, err => { return Promise.reject(err); } );
// http response 拦截器 axios.interceptors.response.use( response => { if (response.data) { let code = response.data.code switch (code) { case 109: // 109 清除token信息并跳转到登录页面 localStorage.aynUserToken = '' // vue.$loginVerify() break; case 110: // vue.$roleVerify() break; } } return response; }, error => { if (error.response) { let status = error.response.status switch (status) { case 401: // 109 清除token信息并跳转到登 大专栏 axios 二次封装录页面 localStorage.aynUserToken = '' // vue.$loginVerify() break; } } let err = error.response ? (error.response.data || error.response) : (error.message || error) return Promise.reject(err) } );
/* 二次封装 */ export default async(type, apiName, url, data, options) => {
let vm = this // url拼接 let path = (apiName != '') ? api[apiName] url : url // url-template let UrlTemplate = template.parse(path) // 格式化地址,若data传入参数是{params:{xx:"xxx",xxx:"xxxx"}}结构的,expand要取{xx:"xxx",xxx:"xxxx"}来格式化url if (data && data.hasOwnProperty("params")) { path = UrlTemplate.expand(data.params) if (!data.params) { data.params = {} } data.params._t = Date.now().toString() } else { path = UrlTemplate.expand(data) if (data) { data._t = Date.now().toString() } }
// 设置 {form: true} post/put data转参数拼接字符串 if (options && options.form) { let opt = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } // 利用 qs 库的stringify() 方法拼接参数字符串 data = qs.stringify(data) options === {} ? options.headers = opt.headers : options = opt } // axios await axios[type](path, data, options).then((res) => { // res.data 才是响应数据 vm.result = res.data }) return vm.result }
|