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