index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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('token')) {
  20. config.data = { openid: getStorage('token'), ...config.data}
  21. config.header.token = getStorage('token');
  22. }
  23. return config
  24. });
  25. request.interceptor.response((response) => { /* 请求之后拦截器 */
  26. if (response.data.code === 0) { // 服务端返回的状态码不等于200,则reject()
  27. if (showToast) {
  28. uni.showToast({
  29. title: response.data.msg || '请求出错,稍后重试',
  30. icon: 'none',
  31. duration: 2000,
  32. mask: true
  33. });
  34. }
  35. }
  36. if (response.data.code === 401) { // 服务端返回的状态码不等于200,则reject()
  37. uni.removeStorageSync('token');
  38. store.commit('LOGIN_TIP', true)
  39. }
  40. // if (response.config.custom.verification) { // 演示自定义参数的作用
  41. // return response.data
  42. // }
  43. return response
  44. }, (response) => { // 预留可以日志上报
  45. uni.showToast({
  46. title: '请求出错,稍后重试',
  47. icon: 'none',
  48. duration: 2000,
  49. mask: true
  50. });
  51. return response
  52. })
  53. return request.request({
  54. url: `${api.url}`,
  55. data,
  56. method: api.method
  57. })
  58. }
  59. function getApiObj(url) {
  60. let apiArray = url.split(".");
  61. let api = apiList;
  62. apiArray.forEach(v => {
  63. api = api[v];
  64. });
  65. return api;
  66. }