index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import http from './interface'
  2. export const $http = (url, method, data, json, isloading=true) => {
  3. //设置请求前拦截器
  4. http.interceptor.request = (config) => {
  5. if(isloading){
  6. uni.showLoading({
  7. title:'加载中...'
  8. })
  9. }
  10. config.header = {
  11. 'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
  12. "token": uni.getStorageSync('token'),
  13. "userId": uni.getStorageSync('userInfo')?JSON.parse(uni.getStorageSync('userInfo')).id:'',
  14. }
  15. }
  16. //设置请求结束后拦截器
  17. http.interceptor.response = async (response) => {
  18. //判断返回状态 执行相应操作
  19. if(isloading){
  20. uni.hideLoading()
  21. }
  22. if (response?.data?.code === 401 || response?.data?.msg.indexOf('未授权') > -1 || response?.data?.msg.indexOf('重新登录') > -1) {
  23. return uni.showModal({
  24. title: '温馨提示',
  25. content:'当前登录已失效,是否返回重新登录',
  26. success: (res) => {
  27. if (res.confirm) {
  28. uni.removeStorageSync('token');
  29. uni.removeStorageSync('userInfo');
  30. uni.reLaunch({
  31. url: '/pages/login/wxLogin'
  32. })
  33. }
  34. }
  35. })
  36. }
  37. // 请根据后端规定的状态码判定
  38. if (response.data.code === 300) {//token失效
  39. // return response.data = await doRequest(response, url)//动态刷新token,并重新完成request请求
  40. }else{
  41. if(response.data.code==10021&&response.data.msg){
  42. uni.showToast({
  43. title:response.data.msg,
  44. icon:'none',
  45. duration:1500
  46. })
  47. }
  48. }
  49. return response;
  50. }
  51. return http.request({
  52. method: method,
  53. url: url,
  54. dataType: 'json',
  55. data,
  56. })
  57. }
  58. function postJson(url, data, isloading=true) {
  59. return $http(url, 'POST', data, isloading)
  60. }
  61. function get(url, data, isloading=true) {
  62. return $http(url, 'GET', data, true, isloading)
  63. }
  64. function post(url, data, isloading=true) {
  65. return $http(url, 'POST', data, true, isloading)
  66. }
  67. function put(url, data, isloading=true) {
  68. return $http(url, 'PUT', data, true, isloading)
  69. }
  70. function del(url, data, isloading=true) {
  71. return $http(url, 'DELETE', data, true, isloading)
  72. }
  73. export default {
  74. postJson,
  75. get,
  76. post,
  77. put,
  78. del
  79. }