request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import config from "@/config"; // 配置文件
  2. import storage from "./storage"; // 缓存封装
  3. export default {
  4. console(options){
  5. if(config.debug){
  6. // console.log("<<===============================================>>");
  7. // console.log("request start");
  8. // console.log("header" + JSON.stringify(options.header));
  9. // console.log("method: " + options.method + " URL: " + options.url);
  10. // console.log(options.data);
  11. // console.log("request end");
  12. // console.log("<<===============================================>>");
  13. }
  14. },
  15. domain(){
  16. return config.uni_app_web_api_url.replace("api","");
  17. },
  18. send(options={}){
  19. // loading加载
  20. // uni.showLoading({
  21. // title: '加载中'
  22. // });
  23. // 拼接路劲,下面的配置文件会提到
  24. options.url = config.uni_app_web_api_url + '' + options.url;
  25. // 请求方式
  26. options.method = options.method || "GET";
  27. // 这里看项目的情况来定,如果是没有token,那就删除这里,上面的storage也不需要引入
  28. let users = storage.getJson("users");
  29. if(users != null){
  30. // options.header = { "user_id" : users.user_id };
  31. options.header = { "user_token" : users.user_token,"user_id" : users.user_id };
  32. // options.headers["user_id"] = users.user_id;
  33. // options.headers["user_token"] = users.user_token;
  34. // options.data['token'] = users.token
  35. }
  36. console.log(options); // 打印请求数据,调试用,上线可以注释
  37. // 发起Promise请求
  38. return new Promise((resolve, reject) =>{
  39. uni.request(options).then(data=>{
  40. var [error, res] = data;
  41. if(error != null){
  42. reject(error);
  43. }else{
  44. // 相应拦截、根据后端的状态码来写,可以自行判断和封装
  45. console.log(res)
  46. if(res.data.code == '-1'){
  47. // uni.showToast({
  48. // icon: 'none',
  49. // title: res.data.message,
  50. // duration: 5000
  51. // });
  52. // uni.reLaunch({
  53. // url: "/pages/login/index",
  54. // success:() => {
  55. // }
  56. // });
  57. uni.hideLoading();
  58. }else{
  59. resolve(res.data);
  60. }
  61. }
  62. uni.hideLoading();
  63. }).catch(data =>{
  64. uni.showToast({
  65. icon: 'none',
  66. title: "服务器错误",
  67. duration: 5000
  68. });
  69. uni.hideLoading();
  70. });
  71. });
  72. },
  73. get(url="",data={}){
  74. return this.send({
  75. url: url,
  76. data: data
  77. });
  78. },
  79. post(url="",data={}){
  80. return this.send({
  81. url: url,
  82. data: data,
  83. method: "POST"
  84. });
  85. }
  86. };