request.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import config from '../config.js'
  2. import {login} from '@/api/login.js'
  3. //请求
  4. function request (req) {
  5. let data = req.data
  6. const method = req.method
  7. const url = req.url
  8. let loading = false
  9. if (req.data.loading){
  10. loading = data.loading
  11. delete data.loading
  12. }
  13. let header = {
  14. 'Content-Type': 'application/json',
  15. 'timestamp': Date.parse(new Date()),
  16. // 'token': uni.getStorageSync('user').access_token,
  17. 'Authorization':'Bearer ' + uni.getStorageSync('user').access_token
  18. }
  19. if (loading){
  20. uni.hideLoading()
  21. uni.showLoading({
  22. title: '请求中',
  23. mask:true
  24. })
  25. }
  26. return new Promise((resolve, reject) => {
  27. console.log('REQ ==>', url)
  28. console.log( data )
  29. uni.request({
  30. url: url,
  31. data: data,
  32. header: header,
  33. method: method.toUpperCase(),
  34. timeout:1000 * 60 * 3, //超时三分钟
  35. success: async (res) => {
  36. uni.hideLoading()
  37. console.log("RES <==", url)
  38. console.log( res )
  39. if (res.statusCode == 200 && res.data.code == 200){
  40. resolve(res.data.data)
  41. }else if (res.statusCode == 401){
  42. //处理token验证出错
  43. console.log('Token过期')
  44. if (!uni.getStorageSync('user')){
  45. //其他设备登录了
  46. uni.reLaunch({
  47. url: '/pages/login/pages/login'
  48. });
  49. }else{
  50. //token续租
  51. let r = await login(uni.getStorageSync('user').login)
  52. let result = await request (req)
  53. }
  54. }else{
  55. console.error(res.data.msg)
  56. if (res.data.msg == '登录状态已过期'){
  57. uni.reLaunch({
  58. url: '/pages/login/pages/login'
  59. })
  60. }
  61. uni.showToast({
  62. title: res.data.msg,
  63. icon: "none",
  64. position:"bottom",
  65. duration: 3000
  66. })
  67. reject(false)
  68. }
  69. },
  70. fail: (err) => {
  71. uni.hideLoading()
  72. uni.showToast({
  73. title: '服务器休息中,请稍后再试',
  74. icon: "none",
  75. position:"center",
  76. duration: 3000
  77. });
  78. console.error(url, err)
  79. reject(err)
  80. }
  81. });
  82. })
  83. }
  84. export default request