request.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import axios from '../js_sdk/xtshadow-axios/axios.min'
  2. import store from '../store'
  3. import {
  4. paramsToStr,
  5. currentPage,
  6. toast
  7. } from './tools'
  8. import Cache from './cache'
  9. import {
  10. TOKEN
  11. } from '../config/cachekey'
  12. import {
  13. baseURL
  14. } from '../config/app'
  15. import {
  16. toLogin
  17. } from './login'
  18. import {
  19. router
  20. } from '../router'
  21. let index = 0;
  22. function checkParams(params) {
  23. if (typeof params != 'object') return params
  24. for (let key in params) {
  25. const value = params[key];
  26. if (value === null || value === undefined || value === "") {
  27. delete params[key];
  28. }
  29. }
  30. return params;
  31. }
  32. const service = axios.create({
  33. baseURL: baseURL + '/api/v1/',
  34. timeout: 10000,
  35. header: {
  36. 'content-type': 'application/x-www-form-urlencoded',
  37. "Access-Control-Allow-Origin": "*",
  38. "Access-Control-Allow-Methods": "*",
  39. "Access-Control-Allow-Headers": "authorization,Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token"
  40. },
  41. });
  42. // request拦截器
  43. service.interceptors.request.use(
  44. config => {
  45. config.data = checkParams(config.data)
  46. config.params = checkParams(config.params)
  47. if (config.method == 'GET') {
  48. config.url += paramsToStr(config.params)
  49. }
  50. config.header.token = store.getters.token
  51. return config
  52. },
  53. error => {
  54. // Do something with request error
  55. console.log(error) // for debug
  56. Promise.reject(error)
  57. }
  58. )
  59. // response 拦截器
  60. service.interceptors.response.use(
  61. async (response) => {
  62. if (response.data) {
  63. const {
  64. status,
  65. show,
  66. info
  67. } = response.data;
  68. if (status == 0) { //错误
  69. toast({
  70. title: info,
  71. })
  72. } else if (status == -1) { //未登录
  73. // toast({
  74. // title: info,
  75. // })
  76. // store.commit('logout')
  77. // toLogin()
  78. } else if (status == 2) { //失败
  79. toast({
  80. title: info,
  81. })
  82. } else if (status == 301) { //重定向
  83. // 返回上一页
  84. toast({
  85. title: info,
  86. }, {
  87. tab: 3,
  88. url: 1
  89. })
  90. }
  91. }
  92. return Promise.resolve(response.data)
  93. },
  94. error => {
  95. uni.showToast({
  96. title: "系统错误",
  97. icon: "none"
  98. })
  99. console.log(error)
  100. console.log('err' + error) // for debug
  101. return Promise.reject(error)
  102. }
  103. )
  104. export default service