axios使用小记
axios类似ajax。下面说说他是如何调用的
调用
XXXX.service.post(URL_ROOT, 'parseRequest', params);
index.js
1 axios.defaults.headers.post['Content-Type'] = 'application/json'; 2 export const URL_ROOT = "/test"; 3 4 //去掉特殊符号 5 function htmlEncodeByRegExp(str) { 6 var s = ""; 7 if (str.length == 0) return ""; 8 s = str.replace(/&/g, "&"); 9 s = s.replace(/</g, "<"); 10 s = s.replace(/>/g, ">"); 11 s = s.replace(/ /g, " "); 12 s = s.replace(/'/g, "\\\'"); 13 s = s.replace(/"/g, "\\\""); 14 return s; 15 }; 16 17 function _response(response, type) { 18 // 统一处理服务端返回值 19 const data = JSON.parse(htmlEncodeByRegExp(JSON.stringify(response.data))); 20 let message = ''; 21 if (response.status === 200) { 22 if (data.code === 200) { 23 return data.data; 24 } else if (data.code === 401) { 25 let aclurl = data.data; 26 window.location.href = decodeURIComponent(aclurl).replace(/\+/g, " "); 27 return data.data 28 } else { 29 message = (data && data.message) || response.statusText || "程序开了下小差,请检查构建包并重新上传。"; 30 } 31 // throw new Error(message); 32 toastMessage(data.code, message); 33 } else { 34 // throw new Error(response.statusText); 35 toastMessage(response.status, response.statusText) 36 } 37 } 38 39 40 41 function toastMessage(code, message) { 42 Toast.error(code + "," + message); 43 } 44 45 46 47 const URL = { 48 dsl: { 49 get: {}, 50 post: { 51 parseRequest: '/aaa/bbb', 52 parseResponse: '/aaa/bbb', 53 }, 54 put: {}, 55 delete: {} 56 } 57 } 58 } 59 } 60 61 export default class Service { 62 // 根据命名空间统一解析进来的数据请求。可自行定义 63 _main(namespace, method, method_string, params) { 64 // let path = getBasicType(namespace); 65 let methodPath = URL[namespace][method][method_string]; 66 if (methodPath === undefined) { 67 showErrorMsg("'api not found!'"); 68 return 69 } 70 71 if (methodPath) { 72 let path = URL_ROOT + methodPath; 73 return this[`_${method}`](path, params); 74 } else { 75 throw new Error('api not found!'); 76 } 77 } 78 79 /** 80 * @param {String} 命名空间 URL中的key 81 * @param {String} 命名空间对应的方法数组中的值 82 * @param {Object} 参数 83 * @return {} 服务端返回值 84 */ 85 86 post(namespace, method_string, params) { 87 return this._main(namespace, 'post', method_string, params); 88 } 89 90 // 创建数据 91 _post(url, params) { 92 return axios.post(url, params) 93 .then(function (response) { 94 return _response(response, 'post'); 95 }).catch((e) => { 96 return _response(e.response, 'post'); 97 }); 98 99 setTimeout(() => { 100 submitIng = false; 101 }, 2000); 102 } 103 104 }