index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import http from './interface'
  2. export const $http = (url, method, data, json, isAuth, isBuffer) => {
  3. let authorization = uni.getStorageSync('authorization') || 'Basic cmVucmVuaW86cmVucmVuaW8=';
  4. let access_token = uni.getStorageSync('access_token') || '';
  5. //设置请求前拦截器
  6. http.interceptor.request = (config) => {
  7. uni.showLoading({
  8. title: '加载中...'
  9. })
  10. config.header = {
  11. 'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
  12. 'access_token':access_token
  13. }
  14. if(isAuth) config.header.authorization = authorization;
  15. if(isBuffer) config.responseType = 'arrayBuffer';
  16. }
  17. //设置请求结束后拦截器
  18. http.interceptor.response = async (response) => {
  19. //判断返回状态 执行相应操作
  20. uni.hideLoading()
  21. if((response.data&&response.data.code&&response.data.code === 401)
  22. || (response.data&&response.data.msg&&(response.data.msg.indexOf('未授权')>-1
  23. || response.data.msg.indexOf('重新登录')>-1))){
  24. return uni.showModal({
  25. title:'温馨提示',
  26. content:'当前登录已失效,是否重新登录?',
  27. success: (res) => {
  28. if(res.confirm){
  29. uni.clearStorageSync();
  30. uni.reLaunch({
  31. url:'/pages/login/index'
  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. async function login() {
  59. return new Promise(resolve => {
  60. uni.login({
  61. provider: 'weixin',
  62. success(loginRes) {
  63. resolve(loginRes.code)
  64. },
  65. fail() {}
  66. });
  67. })
  68. }
  69. function postJson(url, data, json=true, isAuth=true, isBuffer=false) {
  70. return $http(url, 'POST', data, json, isAuth, isBuffer)
  71. }
  72. function get(url, data, json=true, isAuth=true, isBuffer=false) {
  73. return $http(url, 'GET', data, json, isAuth, isBuffer)
  74. }
  75. function post(url, data, json=true, isAuth=true, isBuffer=false) {
  76. return $http(url, 'POST', data, json, isAuth, isBuffer)
  77. }
  78. function put(url, data, json=true, isAuth=true, isBuffer=false) {
  79. return $http(url, 'PUT', data, json, isAuth, isBuffer)
  80. }
  81. function del(url, data, json=true, isAuth=true, isBuffer=false) {
  82. return $http(url, 'DELETE', data, json, isAuth, isBuffer)
  83. }
  84. export default {
  85. postJson,
  86. get,
  87. post,
  88. put,
  89. del
  90. }