index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import ajax from 'uni-ajax'
  2. import {getToken} from '../util/auth';
  3. import website from '@/config/index';
  4. import {Base64} from 'js-base64';
  5. import {toSerialize} from "js-fast-way"
  6. import {getAppApiUrl} from '@/config/envApi';
  7. // 创建请求实例
  8. const instance = ajax.create({
  9. baseURL: getAppApiUrl(),
  10. timeout: 1800000,
  11. validateStatus: function (status) {
  12. return status >= 200 && status <= 500;
  13. },
  14. //跨域请求,允许保存cookie
  15. withCredentials: true,
  16. })
  17. //http request拦截
  18. instance.interceptors.request.use(config => {
  19. const meta = (config.meta || {});
  20. const isToken = meta.isToken === false;
  21. config.header = {...config.headers}
  22. config.header['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  23. //让每个请求携带token
  24. const token = getToken()
  25. if (token && !isToken) {
  26. config.header['Blade-Auth'] = 'bearer ' + token
  27. }
  28. //headers中配置text请求
  29. if (config.text === true) {
  30. config.header["Content-Type"] = "text/plain";
  31. }
  32. //headers中配置serialize为true开启序列化
  33. if (config.method === 'post' && meta.isSerialize === true) {
  34. config.data = toSerialize(config.data);
  35. }
  36. //#ifdef APP-PLUS
  37. config.url = config.url.replace(/^\/api/, '/');
  38. //#endif
  39. config.metadata = { startTime: new Date() }
  40. return config
  41. }, error => {
  42. return Promise.reject(error)
  43. });
  44. //http response 拦截
  45. instance.interceptors.response.use(res => {
  46. //响应时间
  47. res.config.metadata.endTime = new Date()
  48. //获取状态码
  49. const status = res?.data?.code || res.statusCode
  50. //如果是401则跳转到登录页面
  51. if (status === 401) {
  52. uni.showToast({
  53. title: '身份失效',
  54. icon: 'none'
  55. });
  56. uni.redirectTo({
  57. url: '/pages/login/login'
  58. });
  59. }
  60. // 如果请求为非200否者默认统一处理
  61. if (status !== 200) {
  62. return Promise.reject(res)
  63. }
  64. return res;
  65. }, error => {
  66. return Promise.reject(new Error(error));
  67. });
  68. export default instance;