123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- /**
- * Created by Administrator on 2017/9/22.
- */
- // 引用axios
- var axios = require('axios');
- var qs = require('qs');
- // 引用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,success,fail)
- {
- if(params) {
- params = filter_param(params);
- }
- axios({
- method:method,
- url:url,
- data:method == "POST" || method == "PUT" ? initData(params):null,
- params:method === "GET" || method ==="DELETE" ? params:null,
- baseURL: rootUrl,
- withCredentials: false,
- header:{"Content-type":"application/x-www-form-urlencoded"}
- })
- .then(function(res){
- if (res.data) {
- if (success) {
- success(res.data)
- }
- } else {
- if (fail) {
- fail (res.data)
- } else {
- window.alert('error: ' + JSON.stringify(res.data))
- }
- }
- })
- .catch(function (err) {
- let res = err.response
- if (err) {
- window.alert('api error, HTTP CODE: ' + res.status)
- return
- }
- })
- }
- export default {
- get:function(root,url,params,success,fail){
- root = root!=null ? root:"";
- return _api_req(root,"GET","/"+url,params,success,fail);
- },
- put:function(root,url,params,success,fail)
- {
- root = root!=null ? root:"";
- return _api_req(root,"PUT","/"+url,params,success,fail);
- },
- post:function(root,url,params,success,fail)
- {
- root = root!=null ? root:"";
- return _api_req(root,"POST","/"+url,params,success,fail);
- },
- delete:function(root,url,params,success,fail)
- {
- root = root!=null ? root:"";
- return _api_req(root,"DELETE","/"+url,params,success,fail);
- }
- }
|