index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import http from './interface'
  2. export const $http = (url, method, data, json, isAuth, isBuffer) => {
  3. let authorization = uni.getStorageSync('authorization') || '';
  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: ''
  32. })
  33. }
  34. }
  35. })
  36. }
  37. // 请根据后端规定的状态码判定
  38. if (response.data.code === 300) { //token失效
  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. async function login() {
  58. return new Promise(resolve => {
  59. uni.login({
  60. provider: 'weixin',
  61. success(loginRes) {
  62. resolve(loginRes.code)
  63. },
  64. fail() {}
  65. });
  66. })
  67. }
  68. function postJson(url, data, json = true, isAuth = true, isBuffer = false) {
  69. return $http(url, 'POST', data, json, isAuth, isBuffer)
  70. }
  71. function get(url, data, json = true, isAuth = true, isBuffer = false) {
  72. return $http(url, 'GET', data, json, isAuth, isBuffer)
  73. }
  74. function post(url, data, json = true, isAuth = true, isBuffer = false) {
  75. return $http(url, 'POST', data, json, isAuth, isBuffer)
  76. }
  77. function put(url, data, json = true, isAuth = true, isBuffer = false) {
  78. return $http(url, 'PUT', data, json, isAuth, isBuffer)
  79. }
  80. function del(url, data, json = true, isAuth = true, isBuffer = false) {
  81. return $http(url, 'DELETE', data, json, isAuth, isBuffer)
  82. }
  83. export default {
  84. postJson,
  85. get,
  86. post,
  87. put,
  88. del,
  89. }