request.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import config from "@/config";
  2. import storage from "./storage";
  3. import store from "../store/index"
  4. export default {
  5. console(options) {
  6. // if(config.debug){
  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. // }
  13. },
  14. domain() {
  15. return config.uni_app_web_api_url.replace("api", "");
  16. },
  17. send(options = {}) {
  18. options.url = config.uni_app_web_api_url + '' + options.url;
  19. options.method = options.method || "GET";
  20. options.timeout=5000
  21. let users = storage.getJson("userId");
  22. let token = storage.getJson("token");
  23. if (users != null && token != null) {
  24. options.header = {
  25. "Authorization": token
  26. };
  27. }
  28. this.console(options);
  29. return new Promise((resolve, reject) => {
  30. // uni.showLoading({
  31. // title: '加载中...',
  32. // mask: true
  33. // });
  34. uni.request(options).then(data => {
  35. var [error, res] = data;
  36. // console.log(error,'data')
  37. if (error != null) {
  38. reject(error);
  39. if(error.errMsg.includes('timeout')){
  40. uni.showToast({
  41. title: '请求接口失败!',
  42. icon: 'none',
  43. })
  44. }else{
  45. uni.showToast({
  46. title: '网络错误!',
  47. icon: 'none',
  48. })
  49. }
  50. } else {
  51. if (res.data.code == -3) {
  52. storage.remove("users")
  53. storage.remove("token")
  54. store.commit("DELETEUSERS")
  55. uni.reLaunch({
  56. url: '/pages/public/login'
  57. })
  58. } else {
  59. resolve(res.data);
  60. }
  61. }
  62. // uni.hideLoading();
  63. });
  64. });
  65. },
  66. get(url = "", data = {}) {
  67. return this.send({
  68. url: url,
  69. data: data
  70. });
  71. },
  72. post(url = "", data = {}) {
  73. return this.send({
  74. url: url,
  75. data: data,
  76. method: "POST",
  77. });
  78. }
  79. };