axios.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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&&authorization){
  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. if(res[0]&&res[0].errMsg.indexOf('request:fail')>=0){
  25. resolve({
  26. status: 6000,
  27. message: "网络请求失败"
  28. })
  29. }
  30. let ret = res[1]
  31. if(res[1].data.status){
  32. ret = res[1].data
  33. }else if(res[1].status){
  34. ret = res[1]
  35. }
  36. if(ret.status == '200'){
  37. resolve(ret)
  38. }else{
  39. if(ret.status != '401'){
  40. setTimeout(()=>{ // 通过延时避免uni.hideLoading()关闭加载中状态时同时关闭提示信息
  41. uni.showToast({
  42. icon:'none',
  43. title: ret.message,
  44. mask: true,
  45. duration: 5000
  46. })
  47. }, 1000)
  48. }else{
  49. setTimeout(()=>{
  50. uni.showToast({
  51. icon:'none',
  52. title: '未登录或登录已过期,请重新登录',
  53. duration: 5000
  54. })
  55. }, 500)
  56. setTimeout(function() {
  57. const currentRoute = getRoutePath()
  58. const url = `/pages/login/login?lanuch=${currentRoute.lanuch}&path=` + encodeURIComponent(currentRoute.url)
  59. uni.redirectTo({ url })
  60. }, 1000);
  61. }
  62. resolve(ret)
  63. }
  64. resolve(ret)
  65. }
  66. ).catch(
  67. (response) => {
  68. reject(response)
  69. }
  70. )
  71. })
  72. return promise
  73. }
  74. function getRoutePath() {
  75. // eslint-disable-next-line no-undef
  76. const pages = getCurrentPages(); // 获取加载的页面
  77. const currentPage = pages[pages.length - 1]; // 获取当前页面的对象
  78. let url = currentPage.route; // 当前页面url
  79. const options = objToUrl(currentPage.options); // 如果要获取url中所带的参数可以查看options
  80. const lanuch = [
  81. 'pages/index/index'
  82. ].includes(url);
  83. url = '/' + url;
  84. if (options.length) {
  85. url += '?' + options;
  86. }
  87. return {
  88. url,
  89. lanuch
  90. };
  91. }
  92. export default {
  93. baseUrl,
  94. request
  95. }