request.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import Vue from "vue";
  2. import axios from "axios";
  3. import qs from "qs";
  4. import user from "@/store/modules/user";
  5. const instance = axios.create({
  6. baseURL: process.env.VUE_APP_BASE_API,
  7. timeout: 5000,
  8. headers: {
  9. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  10. },
  11. transformRequest: [
  12. data => {
  13. if (typeof data !== "object") return data;
  14. let newData: IAny = {};
  15. Object.keys(data).forEach(key => {
  16. if ([null, undefined, ""].includes(data[key])) return;
  17. if (typeof data[key] === "object") {
  18. data[key] = JSON.stringify(data[key]);
  19. }
  20. newData[key] = data[key];
  21. });
  22. return qs.stringify(newData);
  23. }
  24. ]
  25. });
  26. instance.interceptors.response.use(
  27. x => x,
  28. err => ({
  29. data: {
  30. errno: -1,
  31. errmsg: "网络请求失败",
  32. data: err
  33. }
  34. })
  35. );
  36. const getResult: <T>(x: IBaseResult) => IResult<T> = <T>({
  37. data,
  38. errmsg,
  39. errno
  40. }: IBaseResult<T>) => {
  41. if (errno === 0) return [null, data];
  42. return [{ errno, errmsg }, (data || {}) as T];
  43. };
  44. export const post: IRequest = async <T>(url: string, params: any) => {
  45. const { data } = await instance.post<IBaseResult<T>>(url, params);
  46. return getResult<T>(data);
  47. };
  48. export const get: IRequest = async <T>(url: string, params: any) => {
  49. const { data } = await instance.get<IBaseResult<T>>(url, { params });
  50. return getResult<T>(data);
  51. };
  52. export const post_auth: IRequest = async <T>(url: string, params: any) =>
  53. await post<T>(url, Object.assign({}, params, { token: user.Token }));
  54. export const get_auth: IRequest = async <T>(url: string, params: any) =>
  55. await get<T>(url, Object.assign({}, params, { token: user.Token }));
  56. export default {
  57. install(vue: typeof Vue) {
  58. Object.assign(vue.prototype, {
  59. $get: get,
  60. $post: post,
  61. $get_auth: get_auth,
  62. $post_auth: post_auth
  63. });
  64. }
  65. };