index.js 1.9 KB

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