平安校园
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.

api.js 2.3 KiB

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