index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import http from './interface'
  2. export const $http = (url, method, data, json) => {
  3. //设置请求前拦截器
  4. http.interceptor.request = (config) => {
  5. uni.showLoading({
  6. title:'加载中...'
  7. })
  8. config.header = {
  9. 'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
  10. "token": uni.getStorageSync('tokendata'),
  11. }
  12. }
  13. //设置请求结束后拦截器
  14. http.interceptor.response = async (response) => {
  15. //判断返回状态 执行相应操作
  16. uni.hideLoading()
  17. // 请根据后端规定的状态码判定
  18. // console.log('111111111111111111',response)
  19. if (response.data.code === 300) {//token失效
  20. // return response.data = await doRequest(response, url)//动态刷新token,并重新完成request请求
  21. }else{
  22. if(response.data.code==10021&&response.data.msg){
  23. uni.showToast({
  24. title:response.data.msg,
  25. icon:'none',
  26. duration:1500
  27. })
  28. }
  29. }
  30. return response;
  31. }
  32. return http.request({
  33. method: method,
  34. url: url,
  35. dataType: 'json',
  36. data,
  37. })
  38. }
  39. // async function login() {
  40. // //返回环宇token所需的login code
  41. // return new Promise(resolve => {
  42. // uni.login({
  43. // provider: 'weixin',
  44. // success(loginRes) {
  45. // resolve(loginRes.code)
  46. // },
  47. // fail() {}
  48. // });
  49. // })
  50. // }
  51. // async function doRequest(response, url) {
  52. // //var code = await login()
  53. // var res = await get('/v1/oauth/refreshToken/code/'+code, {})
  54. // if (res && res.data.data.token) {
  55. // let config = response.config
  56. // uni.setStorageSync("token", res.data.data.token);
  57. // config.header['Authorization'] = res.data.data.token
  58. // let json = config.header["Content-Type"] === 'application/json'
  59. // const resold = await $http(url, config.method, {
  60. // ...config.data
  61. // }, json)
  62. // return resold
  63. // } else {
  64. // uni.clearStorage()
  65. // uni.showToast({
  66. // title: "授权失效,请重新登录",
  67. // duration: 1000,
  68. // })
  69. // uni.navigateTo({
  70. // url: '/pages/login/auth'
  71. // })
  72. // return false
  73. // }
  74. // }
  75. function postJson(url, data) {
  76. return $http(url, 'POST', data)
  77. }
  78. function get(url, data) {
  79. return $http(url, 'GET', data, true)
  80. }
  81. function post(url, data) {
  82. return $http(url, 'POST', data, true)
  83. }
  84. function put(url, data) {
  85. return $http(url, 'PUT', data, true)
  86. }
  87. function del(url, data) {
  88. return $http(url, 'DELETE', data, true)
  89. }
  90. export default {
  91. postJson,
  92. get,
  93. post,
  94. put,
  95. del
  96. }