/** * Created by Administrator on 2017/9/22. */ // 引用axios var axios = require('axios'); var qs = require('qs'); axios.interceptors.request.use((config)=>{ if(config && config.method == "post" && config.url.indexOf("filemanager")==-1) { if(config.data) { config.data = filter_param(config.data); } config.data = qs.stringify(config.data); config.headers["Content-Type"]="application/x-www-form-urlencoded"; } else if(config && config.method == "get" && config.url.indexOf("filemanager")==-1) { if(config.data) { config.data = filter_param(config.data); } } return config; }) // 引用superagent //自定义判断元素类型 function toType(obj) { return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); } // 参数过滤函数 function filter_param(o) { for(var key in o) { if(o[key]==null) delete o[key]; if(toType(o[key])=="string") { o[key] = o[key].trim(); if(o[key].length==0) { delete o[key]; } } } return o; } function initData(params) { var formMap = new URLSearchParams(); for(var key in params){ formMap.append(key, params[key]); } return formMap; } /* 接口处理函数 */ function _api_req(rootUrl,method,url,params,headers,callback1,callback2,errCallback) { if(process.env.NODE_ENV === 'production') { rootUrl = "/"; } return axios({ method:method, url:url, data:method == "POST" || method == "PUT" ? params:null, params:method === "GET" || method ==="DELETE" ? params:null, baseURL: rootUrl, withCredentials: false, headers:headers, onUploadProgress:function(progressEvent){ //原生获取上传进度的事件 if(progressEvent.lengthComputable){ //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量 //如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded if(callback1) { callback1(progressEvent); } } }, }).then(res =>{ callback2(res.data); },error =>{ errCallback(error); }) } export default { get:function(root,url,params,headers,callback1,callback2,errCallback){ root = root!=null ? root:""; return _api_req(root,"GET","/"+url,params,headers,callback1,callback2,errCallback); }, put:function(root,url,params,headers,callback1,callback2,errCallback) { root = root!=null ? root:""; return _api_req(root,"PUT","/"+url,params,headers,callback1,callback2,errCallback); }, post:function(root,url,params,headers,callback1,callback2,errCallback) { root = root!=null ? root:""; return _api_req(root,"POST","/"+url,params,headers,callback1,callback2,errCallback); }, delete:function(root,url,params,headers,callback1,callback2,errCallback) { root = root!=null ? root:""; return _api_req(root,"DELETE","/"+url,params,headers,callback1,callback2,errCallback); } }