index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import request from './request.js' // 文档地址:https://github.com/jerry-9527/uni_request
  2. import config from '@/config/config.js'
  3. // import store from '@/store'
  4. import cache from '@/utils/cache'
  5. import {
  6. LOGIN_TOKEN,
  7. CLIENT_ID
  8. } from '@/config/cache'
  9. // 创建request实例
  10. const service = request({
  11. baseURL: config.baseUrl,
  12. timeout: 5000, // 请求超时,
  13. header: {
  14. 'Content-Type': 'application/x-www-form-urlencoded',
  15. 'Accept': 'application/json'
  16. }
  17. });
  18. // 请求拦截器
  19. service.interceptors.request.use(async (config, ...args) => {
  20. // 判断token是否存在
  21. let token = cache.get(LOGIN_TOKEN) || '';
  22. // token为空已过期 刷新token
  23. if (token) {
  24. config.body.token = token;
  25. }
  26. return config
  27. })
  28. // response interceptor
  29. service.interceptors.response.use((response, ...args) => { // 响应拦截器(可以设置多个, 同时可以也可以使用异步方法)
  30. // 状态403token无效 清除token
  31. if (response.data.errorCode == 403) {
  32. cache.set(LOGIN_TOKEN, '');
  33. }
  34. if (response.data.message) {
  35. uni.showToast({
  36. title: response.data.message,
  37. duration: 1500,
  38. mask: true,
  39. icon: 'none'
  40. });
  41. }
  42. return response
  43. })
  44. export default service