耀实惠小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.9 KiB

  1. import Request from './request'
  2. import apiList from './shopro'
  3. import utils from '@/utils/utils.js'
  4. // import store from '@/common/store/index.js'
  5. import { TOKEN_HEADER_NAME } from '@/config/settings.js'
  6. import { storageKeys, storage } from '@/utils/storage.js'
  7. export default function api(url, data = {}) {
  8. const request = new Request();
  9. let api = getApiObj(url);
  10. request.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
  11. let userToken = storage.getStorage(storageKeys.TOKEN) || ''
  12. if (api.auth) {
  13. if (!userToken) {
  14. console.log(config)
  15. // 去登录
  16. utils.loginModal('您还未登录,请进行登录!')
  17. throw('暂未登录,已阻止此次API请求~');
  18. }
  19. }
  20. if (userToken) {
  21. config.header[TOKEN_HEADER_NAME] = storage.getStorage(storageKeys.TOKEN)
  22. }
  23. return config
  24. });
  25. request.interceptor.response((response) => { /* 请求之后拦截器 */
  26. // if (response.data.code === 0) { // 服务端返回的状态码不等于200,则reject()
  27. // uni.showToast({
  28. // title: response.data.msg || '请求出错,稍后重试',
  29. // icon: 'none',
  30. // duration: 1000,
  31. // mask: true
  32. // });
  33. // }
  34. if (response.data.code === 401 || response.data.message.indexOf('Token失效') > -1) { // 服务端返回的状态码不等于200,则reject()
  35. uni.hideLoading()
  36. utils.loginModal('登录过期,请重新登录!')
  37. return
  38. }
  39. // if (response.config.custom.verification) { // 演示自定义参数的作用
  40. // return response.data
  41. // }
  42. return response
  43. }, (response) => { // 预留可以日志上报
  44. return response
  45. })
  46. let option = {
  47. url: api.url,
  48. data,
  49. method: api.method
  50. }
  51. if (api.headers!=null){
  52. option.header = api.headers
  53. }
  54. return request.request(option)
  55. }
  56. function getApiObj(url) {
  57. let apiArray = url.split(".");
  58. let api = apiList;
  59. apiArray.forEach(v => {
  60. api = api[v];
  61. });
  62. return api;
  63. }