http.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import { useStorage } from '@vueuse/core'
  4. const baseURL = import.meta.env.VITE_BASE_URL
  5. const axiosInstance = axios.create({ baseURL })
  6. const token = useStorage('token', '', sessionStorage)
  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: '网络错误,请检查网络链接'
  19. }
  20. } else {
  21. errorData = error.response.data
  22. }
  23. if (typeof errorData != 'object') {
  24. errorData = {
  25. error: '请求失败' + error.response.status
  26. }
  27. }
  28. return Promise.reject(errorData)
  29. }
  30. )
  31. const http = {
  32. setToken(_token) {
  33. token.value = _token
  34. if (_token) {
  35. axiosInstance.defaults.headers.common['Authorization'] = 'Bearer ' + _token
  36. } else {
  37. axiosInstance.defaults.headers.common['Authorization'] = null
  38. }
  39. },
  40. async login(phone, password) {
  41. let { data: token } = await axiosInstance.post('/auth/phonePwdLogin', qs.stringify({ phone, password }))
  42. this.setToken(token)
  43. },
  44. get(url, params) {
  45. return new Promise((resolve, reject) => {
  46. axiosInstance
  47. .get(url, { params, withCredentials: true })
  48. .then(res => {
  49. resolve(res.data)
  50. })
  51. .catch(e => {
  52. reject(e)
  53. })
  54. })
  55. },
  56. post(url, body, options) {
  57. options = options || {}
  58. body = body || {}
  59. if (!(body instanceof FormData)) {
  60. if (options.body !== 'json') {
  61. body = qs.stringify(body)
  62. }
  63. }
  64. return new Promise((resolve, reject) => {
  65. axiosInstance
  66. .post(url, body, { withCredentials: true })
  67. .then(res => {
  68. resolve(res.data)
  69. })
  70. .catch(e => {
  71. reject(e)
  72. })
  73. })
  74. }
  75. }
  76. export default {
  77. install: app => {
  78. app.config.globalProperties.$http = http
  79. app.provide('http', app.config.globalProperties.$http)
  80. },
  81. http
  82. }
  83. export { http }