api.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {
  2. clientId,
  3. clientSecret
  4. } from '@/common/setting'
  5. import {
  6. options
  7. } from '@/http/config.js';
  8. import {
  9. Base64
  10. } from '@/utils/base64.js';
  11. import Request from '@/utils/luch-request/index.js';
  12. const http = new Request(options);
  13. http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  14. // 假设有token值需要在头部需要携带
  15. let accessToken = uni.getStorageSync('accessToken');
  16. if (accessToken) {
  17. config.header['Blade-Auth'] = 'bearer ' + accessToken;
  18. }
  19. // 安全请求header
  20. config.header['Blade-Requested-With'] = 'BladeHttpRequest';
  21. // 客户端认证参数
  22. config.header['Authorization'] = 'Basic ' + Base64.encode(clientId + ':' + clientSecret);
  23. // #ifndef H5
  24. let url = config.url
  25. if (process.env.NODE_ENV == 'development' && !url.startsWith("http")) {
  26. url = url.substring(url.indexOf('/api') + 4)
  27. config.url = url
  28. }
  29. // #endif
  30. // 额外参数
  31. // config.data = config.data || {};
  32. // config.data.pf = uni.getSystemInfoSync().platform;
  33. // config.data.sys = uni.getSystemInfoSync().system;
  34. // 演示custom 用处
  35. // if (config.custom.auth) {
  36. // config.header.token = 'token'
  37. // }
  38. // if (config.custom.loading) {
  39. // uni.showLoading()
  40. // }
  41. /**
  42. /* 演示
  43. if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求
  44. return Promise.reject(config)
  45. }
  46. **/
  47. return config
  48. }, config => { // 可使用async await 做异步操作
  49. return Promise.reject(config)
  50. })
  51. http.interceptors.response.use((response) => {
  52. // 若有数据返回则通过
  53. if (response.data.access_token || response.data.key) {
  54. return response.data
  55. }
  56. // 服务端返回的状态码不等于200,则reject()
  57. if (response.data.code !== 200) {
  58. uni.showToast({
  59. title: response.data.msg,
  60. icon: 'none'
  61. });
  62. return Promise.reject(response);
  63. }
  64. return response.data;
  65. }, (response) => {
  66. /* 对响应错误做点什么 (statusCode !== 200)*/
  67. uni.showToast({
  68. title: response.data.msg,
  69. icon: 'none'
  70. });
  71. if (response.statusCode == 401) {
  72. const pages = getCurrentPages()
  73. const currentPage = pages[pages.length - 1]
  74. uni.redirectTo({
  75. url: `/pages/login/login-account?redirect=/${currentPage.route}`
  76. })
  77. }
  78. return Promise.reject(response)
  79. })
  80. export default http;