index.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import axios, { AxiosRequestConfig, Method } from 'axios'
  2. //import qs from 'qs'
  3. //import cryptojs from 'crypto-js'
  4. import { addPending, removePending } from './pending'
  5. import { getLoginInfo } from '@/business/common'
  6. import { HttpRequest, HttpResponse, ResultCode } from './interface'
  7. //import service from '@/services'
  8. const http = axios.create({
  9. timeout: 30000,
  10. })
  11. /**
  12. * 请求拦截器
  13. */
  14. http.interceptors.request.use(
  15. (config) => {
  16. removePending(config); //在请求开始前,对之前的请求做检查取消操作
  17. addPending(config); //将当前请求添加到列表中
  18. //请求头签名
  19. const sign = {
  20. token: getLoginInfo('Token'),
  21. signsecret: 'qz7qWOMXKTMT5JlDs5w4NTPwWeR3xhF1v6wqbZ9cExmP6cc3spvNAp1wJJ1SqRI5',
  22. timestamp: new Date().getTime(),
  23. };
  24. //设置请求头
  25. config.headers = {
  26. Authorization: sign.token,
  27. //Signid: 'eecd3f37625f4501b88e9f0fa14b4b51',
  28. //Sign: cryptojs.SHA256(qs.stringify(sign)).toString(),
  29. //Timestamp: sign.timestamp.toString(),
  30. };
  31. return config;
  32. },
  33. (error) => {
  34. //此处异常触发条件不明
  35. console.error(error);
  36. return Promise.reject('网络异常,请稍后再试');
  37. }
  38. )
  39. /**
  40. * 响应拦截器
  41. */
  42. http.interceptors.response.use(
  43. (response) => {
  44. removePending(response); //在请求结束后,移除本次请求
  45. return response;
  46. },
  47. (error) => {
  48. if (!axios.isCancel(error)) {
  49. console.error(error);
  50. }
  51. return Promise.reject('服务器异常,请稍后再试');
  52. }
  53. )
  54. /**
  55. * Http请求
  56. */
  57. export async function httpRequest<T extends { req?: unknown, rsp?: unknown }>(url: string, method: Method, params: HttpRequest<T>) {
  58. const { success, fail, complete } = params;
  59. //const { goCommonSearchUrl } = service.config;
  60. const requestConfig: AxiosRequestConfig = {
  61. url,
  62. method: method,
  63. }
  64. if (['post', 'POST', 'put', 'PUT', 'patch', 'PATCH'].includes(method)) {
  65. requestConfig.data = params.data ?? {};
  66. } else {
  67. requestConfig.params = params.data ?? {};
  68. }
  69. await http(requestConfig).then((res) => {
  70. const data = res.data as HttpResponse<T['rsp']>;
  71. switch (data.code) {
  72. case ResultCode.InvalidToken:
  73. //退出登录
  74. //store.dispatch("user/logout", () => {
  75. // window.location.reload();
  76. //});
  77. return Promise.reject('令牌无效');
  78. case ResultCode.Success:
  79. success && success(data);
  80. return Promise.resolve();
  81. default:
  82. return Promise.reject(data.msg);
  83. }
  84. }).catch((err) => {
  85. fail && fail(err);
  86. return Promise.reject(err);
  87. }).finally(() => {
  88. complete && complete();
  89. })
  90. }