http.js 2.7 KB

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