axios.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { objToUrl } from '@/libs/tools.js';
  2. const baseUrl = getApp().globalData.baseUrl
  3. //带Token请求
  4. const request = (opts, hasToken) => {
  5. const authorization = getApp().globalData.token
  6. // console.log(authorization,'authorization')
  7. // hasToken是否传入token,为true则不传token
  8. const header = {
  9. 'Content-Type': 'application/json;charset=UTF-8'
  10. }
  11. if(!hasToken){
  12. header['X-AUTH-TOKEN'] = authorization
  13. }
  14. //此token是登录成功后后台返回保存在storage中的
  15. let DefaultOpts = {
  16. url: baseUrl+opts.url,
  17. data: opts.data,
  18. method: opts.method,
  19. header: opts.header ? opts.header : header
  20. }
  21. let promise = new Promise(function(resolve, reject) {
  22. uni.request(DefaultOpts).then(
  23. (res) => {
  24. // console.log(res[1])
  25. // 是否超时已跳转
  26. let loginTimeOut = uni.getStorageSync('loginTimeOut');
  27. if(res[0]&&res[0].errMsg.indexOf('request:fail')>=0){
  28. resolve({
  29. status: 500,
  30. message: "请求网络失败"
  31. })
  32. }
  33. let ret = res[1]
  34. if(res[1].data.status){
  35. ret = res[1].data
  36. }else if(res[1].status){
  37. ret = res[1]
  38. }
  39. if(ret.status == '200'){
  40. resolve(ret)
  41. }else{
  42. if(ret.status == 401 && loginTimeOut == 'NO'){ // 未登录或登录过期
  43. uni.showToast({
  44. icon:'none',
  45. title: ret.message,
  46. duration: 5000
  47. })
  48. setTimeout(function() {
  49. const currentRoute = getRoutePath();
  50. const url = `/pages/login/login?lanuch=${currentRoute.lanuch}&path=` + encodeURIComponent(currentRoute.url);
  51. uni.reLaunch({ url });
  52. }, 1000);
  53. uni.setStorageSync('loginTimeOut', 'YES');
  54. }
  55. // 503
  56. if(ret.status == '503'){
  57. uni.showToast({
  58. icon:'none',
  59. title: ret.message,
  60. duration: 3000
  61. })
  62. }
  63. resolve(ret)
  64. }
  65. resolve(ret)
  66. }
  67. ).catch(
  68. (response) => {
  69. reject(response)
  70. }
  71. )
  72. })
  73. return promise
  74. }
  75. function getRoutePath() {
  76. // eslint-disable-next-line no-undef
  77. const pages = getCurrentPages(); // 获取加载的页面
  78. const currentPage = pages[pages.length - 1]; // 获取当前页面的对象
  79. let url = currentPage.route; // 当前页面url
  80. const options = objToUrl(currentPage.options); // 如果要获取url中所带的参数可以查看options
  81. const lanuch = [
  82. 'pages/index/index'
  83. ].includes(url);
  84. url = '/' + url;
  85. if (options.length) {
  86. url += '?' + options;
  87. }
  88. return {
  89. url,
  90. lanuch
  91. };
  92. }
  93. export default {
  94. baseUrl,
  95. request
  96. }