axios.api.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * Created by Administrator on 2017/9/22.
  3. */
  4. // 引用axios
  5. var axios = require('axios');
  6. var qs = require('qs');
  7. // 引用superagent
  8. //自定义判断元素类型
  9. function toType(obj)
  10. {
  11. return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
  12. }
  13. // 参数过滤函数
  14. function filter_param(o)
  15. {
  16. for(var key in o)
  17. {
  18. if(o[key]==null)
  19. delete o[key];
  20. if(toType(o[key])=="string")
  21. {
  22. o[key] = o[key].trim();
  23. if(o[key].length==0)
  24. {
  25. delete o[key];
  26. }
  27. }
  28. }
  29. return o;
  30. }
  31. function initData(params)
  32. {
  33. var formMap = new URLSearchParams();
  34. for(var key in params){
  35. formMap.append(key, params[key]);
  36. }
  37. return formMap;
  38. }
  39. /*
  40. 接口处理函数
  41. */
  42. function _api_req(rootUrl,method,url,params,success,fail)
  43. {
  44. if(params) {
  45. params = filter_param(params);
  46. }
  47. axios({
  48. method:method,
  49. url:url,
  50. data:method == "POST" || method == "PUT" ? initData(params):null,
  51. params:method === "GET" || method ==="DELETE" ? params:null,
  52. baseURL: rootUrl,
  53. withCredentials: false,
  54. header:{"Content-type":"application/x-www-form-urlencoded"}
  55. })
  56. .then(function(res){
  57. if (res.data) {
  58. if (success) {
  59. success(res.data)
  60. }
  61. } else {
  62. if (fail) {
  63. fail (res.data)
  64. } else {
  65. window.alert('error: ' + JSON.stringify(res.data))
  66. }
  67. }
  68. })
  69. .catch(function (err) {
  70. let res = err.response
  71. if (err) {
  72. window.alert('api error, HTTP CODE: ' + res.status)
  73. return
  74. }
  75. })
  76. }
  77. export default {
  78. get:function(root,url,params,success,fail){
  79. root = root!=null ? root:"";
  80. return _api_req(root,"GET","/"+url,params,success,fail);
  81. },
  82. put:function(root,url,params,success,fail)
  83. {
  84. root = root!=null ? root:"";
  85. return _api_req(root,"PUT","/"+url,params,success,fail);
  86. },
  87. post:function(root,url,params,success,fail)
  88. {
  89. root = root!=null ? root:"";
  90. return _api_req(root,"POST","/"+url,params,success,fail);
  91. },
  92. delete:function(root,url,params,success,fail)
  93. {
  94. root = root!=null ? root:"";
  95. return _api_req(root,"DELETE","/"+url,params,success,fail);
  96. }
  97. }