request.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import Vue from "vue";
  2. import axios from "axios";
  3. // import md5 from "js-md5";
  4. const instance = axios.create({
  5. baseURL: process.env.VUE_APP_BASE_API,
  6. timeout: 30000,
  7. withCredentials: true
  8. });
  9. // const appKey = "cd72c223-923f-44a3-aede-b9f07dcd56b8";
  10. // const plat = "steelfurniture";
  11. // const v = "1.0";
  12. instance.interceptors.request.use(
  13. ({ headers: { timestamp = Date.now(), token = "", ...h }, ...x }) => ({
  14. headers: {
  15. timestamp,
  16. // appKey,
  17. // plat,
  18. // v,
  19. // sign: md5(`timestamp${timestamp}plat${plat}v${v}appKey${appKey}`),
  20. token,
  21. ...h
  22. },
  23. ...x
  24. })
  25. );
  26. instance.interceptors.response.use(
  27. x => x,
  28. err => ({
  29. data: {
  30. code: -100,
  31. data: err
  32. }
  33. })
  34. );
  35. const getResult: <T>(x: IBaseResult) => IResult<T> = <T>({
  36. data,
  37. code,
  38. msg
  39. }: IBaseResult<T>) => {
  40. if (code === 0) return [null, data];
  41. // Message.error(getErrMsg(code));
  42. return [{ code, msg }, (data || {}) as T];
  43. };
  44. export const post: IRequest = async <T>(url: string, params: any) => {
  45. params.datedate= new Date().getTime();
  46. const { data } = await instance.post<IBaseResult<T>>(url, params);
  47. return getResult<T>(data);
  48. };
  49. export const get: IRequest = async <T>(url: string, params: any) => {
  50. params.datedate= new Date().getTime();
  51. const {data} = await instance.get<IBaseResult<T>>(url, {params});
  52. return getResult<T>(data);
  53. };
  54. export default {
  55. install(vue: typeof Vue) {
  56. Object.assign(vue.prototype, {
  57. $get: get,
  58. $post: post
  59. });
  60. }
  61. };