api.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. // 客户端认证参数
  20. config.header['Authorization'] = 'Basic ' + Base64.encode(clientId + ':' + clientSecret);
  21. // 额外参数
  22. // config.data = config.data || {};
  23. // config.data.pf = uni.getSystemInfoSync().platform;
  24. // config.data.sys = uni.getSystemInfoSync().system;
  25. // 演示custom 用处
  26. // if (config.custom.auth) {
  27. // config.header.token = 'token'
  28. // }
  29. // if (config.custom.loading) {
  30. // uni.showLoading()
  31. // }
  32. /**
  33. /* 演示
  34. if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求
  35. return Promise.reject(config)
  36. }
  37. **/
  38. return config
  39. }, config => { // 可使用async await 做异步操作
  40. return Promise.reject(config)
  41. })
  42. http.interceptors.response.use((response) => {
  43. // 若有数据返回则通过
  44. if (response.data.access_token || response.data.key) {
  45. return response.data
  46. }
  47. // 服务端返回的状态码不等于200,则reject()
  48. if (response.data.code !== 200) {
  49. if (response.data.code) {
  50. return Promise.reject(response);
  51. } else {
  52. return response.data;
  53. }
  54. }
  55. return response.data;
  56. }, (response) => {
  57. /* 对响应错误做点什么 (statusCode !== 200)*/
  58. if (response.data.code === 401) {
  59. uni.showModal({
  60. title: '提示',
  61. content: '登录状态失效,点击确定重新登录',
  62. showCancel: false,
  63. success: function(res) {
  64. if (res.confirm) {
  65. uni.reLaunch({
  66. url: '/pages/login/login'
  67. });
  68. }
  69. }
  70. });
  71. } else if (response.data.error === "unauthorized") {
  72. if (response.data.error_description) {
  73. uni.showToast({
  74. title: response.data.error_description,
  75. icon: 'none'
  76. });
  77. } else {
  78. uni.showToast({
  79. title: response.data.error,
  80. icon: 'none'
  81. });
  82. }
  83. } else if (response.data.error == "invalid_grant") {
  84. uni.showToast({
  85. title: response.data.error_description,
  86. icon: 'none'
  87. });
  88. } else {
  89. uni.showToast({
  90. title: response.data.msg,
  91. icon: 'none'
  92. });
  93. }
  94. return Promise.reject(response.data)
  95. })
  96. export default http;