index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.clearStorageSync();
  29. }
  30. }
  31. })
  32. }
  33. // 请根据后端规定的状态码判定
  34. if (response.data.code === 300) {//token失效
  35. // return response.data = await doRequest(response, url)//动态刷新token,并重新完成request请求
  36. }else{
  37. if(response.data.code==10021&&response.data.msg){
  38. uni.showToast({
  39. title:response.data.msg,
  40. icon:'none',
  41. duration:1500
  42. })
  43. }
  44. }
  45. return response;
  46. }
  47. return http.request({
  48. method: method,
  49. url: url,
  50. dataType: 'json',
  51. data,
  52. })
  53. }
  54. function postJson(url, data, isloading=true) {
  55. return $http(url, 'POST', data, isloading)
  56. }
  57. function get(url, data, isloading=true) {
  58. return $http(url, 'GET', data, true, isloading)
  59. }
  60. function post(url, data, isloading=true) {
  61. return $http(url, 'POST', data, true, isloading)
  62. }
  63. function put(url, data, isloading=true) {
  64. return $http(url, 'PUT', data, true, isloading)
  65. }
  66. function del(url, data, isloading=true) {
  67. return $http(url, 'DELETE', data, true, isloading)
  68. }
  69. export default {
  70. postJson,
  71. get,
  72. post,
  73. put,
  74. del
  75. }