index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import Request from './request'
  2. import apiList from './api_list.js'
  3. import store from '@/store/index.js'
  4. import { setStorage, getStorage } from "@/util/index.js"
  5. export default function api(url, data = {}, showToast = true) {
  6. const request = new Request();
  7. let api = getApiObj(url);
  8. request.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
  9. if (api.auth) {
  10. let token = getStorage('token');
  11. if (!token) {
  12. // store.dispatch('loginOut')
  13. throw ('暂未登录,已阻止此次API请求~');
  14. }
  15. }
  16. if (getStorage('openid')){
  17. config.header.openid = getStorage('openid')
  18. }
  19. if (getStorage('openid')) {
  20. if(config.data.openid === null){
  21. delete config.data.openid
  22. delete config.data.phone
  23. config.data = { ...config.data}
  24. }else{
  25. config.data = { openid: getStorage('openid'), ...config.data}
  26. }
  27. config.header.token = getStorage('openid');
  28. }
  29. return config
  30. });
  31. request.interceptor.response((response) => { /* 请求之后拦截器 */
  32. if (response.data.code === 0) { // 服务端返回的状态码不等于200,则reject()
  33. if (showToast) {
  34. uni.showToast({
  35. title: response.data.msg || '请求出错,稍后重试',
  36. icon: 'none',
  37. duration: 2000,
  38. mask: true
  39. });
  40. }
  41. }
  42. if (response.data.code === 401) { // 服务端返回的状态码不等于200,则reject()
  43. uni.removeStorageSync('token');
  44. store.commit('LOGIN_TIP', true)
  45. }
  46. // if (response.config.custom.verification) { // 演示自定义参数的作用
  47. // return response.data
  48. // }
  49. return response
  50. }, (response) => { // 预留可以日志上报
  51. uni.showToast({
  52. title: '请求出错,稍后重试',
  53. icon: 'none',
  54. duration: 2000,
  55. mask: true
  56. });
  57. return response
  58. })
  59. return request.request({
  60. url: `${api.url}`,
  61. data,
  62. method: api.method
  63. })
  64. }
  65. function getApiObj(url) {
  66. let apiArray = url.split(".");
  67. let api = apiList;
  68. apiArray.forEach(v => {
  69. api = api[v];
  70. });
  71. return api;
  72. }