api.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * Created by Administrator on 2017/9/22.
  3. */
  4. // 配置API接口地址
  5. var root = 'crmServiceInfo';
  6. // 引用superagent
  7. var request = require('superagent');
  8. // 引用superagent
  9. //自定义判断元素类型
  10. function toType(obj)
  11. {
  12. return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
  13. }
  14. // 参数过滤函数
  15. function filter_param(o)
  16. {
  17. for(var key in o)
  18. {
  19. if(o[key]==null)
  20. delete o[key];
  21. if(toType(o[key])=="string")
  22. {
  23. o[key] = o[key].trim();
  24. if(o[key].length==0)
  25. {
  26. delete o[key];
  27. }
  28. }
  29. }
  30. return o;
  31. }
  32. /*
  33. 接口处理函数
  34. */
  35. function _api_req(method,url,params,success,fail)
  36. {
  37. var res = request(method,url).type("text/plain");
  38. if(params)
  39. {
  40. params = filter_param(params);
  41. if(method == "POST" || method == "PUT")
  42. {
  43. if(toType(params) === "object")
  44. {
  45. params = JSON.Stringify(params);
  46. }
  47. res.send(params);
  48. }
  49. else if(method === "GET" || method ==="DELETE")
  50. {
  51. res.query(params);
  52. }
  53. }
  54. res.end(function(err,r){
  55. if(err)
  56. {
  57. alert("请求出错,错误信息:"+r.status);
  58. return;
  59. }
  60. if(r.body)
  61. {
  62. if(success)
  63. {
  64. success(r.body);
  65. }
  66. }
  67. else
  68. {
  69. if(fail)
  70. {
  71. fail(r.body);
  72. }
  73. else
  74. {
  75. alert("err:"+JSON.stringify(r.body));
  76. }
  77. }
  78. })
  79. }
  80. export default {
  81. get:function(url,params,success,fail){
  82. return _api_req("GET",root+"/"+url,params,success,fail);
  83. },
  84. put:function(url,params,success,fail)
  85. {
  86. return _api_req("PUT",root+"/"+url,params,success,fail);
  87. },
  88. post:function(url,params,success,fail)
  89. {
  90. return _api_req("POST",root+"/"+url,params,success,fail);
  91. },
  92. delete:function(url,params,success,fail)
  93. {
  94. return _api_req("DELETE",root+"/"+url,params,success,fail);
  95. }
  96. }