http.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import axios from "axios";
  2. import qs from "qs";
  3. import { useStorage } from "@vueuse/core";
  4. import { App } from "vue";
  5. const baseURL = import.meta.env.VITE_API_BASE_URL;
  6. const axiosInstance = axios.create({
  7. baseURL,
  8. headers: { "Accept-Language": "en-US,en" },
  9. });
  10. const token = useStorage("appToken", "", localStorage);
  11. if (token.value) {
  12. axiosInstance.defaults.headers.common["Authorization"] =
  13. "Bearer " + token.value;
  14. }
  15. axiosInstance.interceptors.response.use(
  16. function (response) {
  17. return response;
  18. },
  19. function (error) {
  20. let errorData = {};
  21. if (!error.response) {
  22. errorData = {
  23. error: "Network Error",
  24. };
  25. } else {
  26. errorData = error.response.data;
  27. }
  28. if (typeof errorData != "object") {
  29. errorData = {
  30. error: "Request failed: " + error.response.status,
  31. };
  32. }
  33. return Promise.reject(errorData);
  34. }
  35. );
  36. const http = {
  37. install: (app: App) => {
  38. app.config.globalProperties.$http = http;
  39. app.provide("http", app.config.globalProperties.$http);
  40. },
  41. token,
  42. baseURL,
  43. resolve(path: string) {
  44. let base = baseURL;
  45. if (!baseURL.startsWith("http")) {
  46. base = new URL(baseURL, window.location.origin).href;
  47. }
  48. return new URL(path, base).href;
  49. },
  50. setToken(_token: string) {
  51. token.value = _token;
  52. if (_token) {
  53. axiosInstance.defaults.headers.common["Authorization"] =
  54. "Bearer " + _token;
  55. } else {
  56. axiosInstance.defaults.headers.common["Authorization"] = null;
  57. }
  58. },
  59. async login(phone: string, password: string) {
  60. const { data: token } = await axiosInstance.post(
  61. "/auth/login",
  62. qs.stringify({ phone, password })
  63. );
  64. this.setToken(token);
  65. },
  66. get(url: string, params?: any): Promise<any> {
  67. return new Promise((resolve, reject) => {
  68. axiosInstance
  69. .get(url, { params, withCredentials: true })
  70. .then((res) => {
  71. resolve(res.data);
  72. })
  73. .catch((e) => {
  74. reject(e);
  75. });
  76. });
  77. },
  78. post(url: string, body: any, options: any) {
  79. options = options || {};
  80. body = body || {};
  81. if (!(body instanceof FormData)) {
  82. if (options.body !== "json") {
  83. body = qs.stringify(body);
  84. }
  85. }
  86. return new Promise((resolve, reject) => {
  87. axiosInstance
  88. .post(url, body, { withCredentials: true })
  89. .then((res) => {
  90. resolve(res.data);
  91. })
  92. .catch((e) => {
  93. reject(e);
  94. });
  95. });
  96. },
  97. };
  98. export default http;