You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.2 KiB

10 months ago
5 months ago
10 months ago
  1. import Axios from 'axios'
  2. import { message } from 'antd'
  3. import { store } from '@/store'
  4. import { HashRouter } from 'react-router-dom'
  5. interface AxiosConfig {
  6. baseURL: string;
  7. timeout: number;
  8. headers: {
  9. 'Content-Type': string
  10. };
  11. }
  12. export const getBaseUrl = () => {
  13. return `http://192.168.124.20:8008/api/v1`
  14. // return `https://apk.buzz-up.io/api/v1`
  15. }
  16. const config: AxiosConfig = {
  17. // baseURL: process.env.REACT_APP_BASE_URL,
  18. baseURL: getBaseUrl(),
  19. timeout: 60 * 1000,
  20. headers: {
  21. 'Content-Type': 'application/json'
  22. }
  23. }
  24. const axios = Axios.create(config)
  25. const router: CommonObjectType = new HashRouter({})
  26. // token失效,清除用户信息并返回登录界面
  27. const clearAll = () => {
  28. store.dispatch({
  29. type: 'SET_USERINFO',
  30. payload: {}
  31. })
  32. router.history.replace({ pathname: '/login' })
  33. }
  34. // 请求前拦截
  35. axios.interceptors.request.use(
  36. (req) => {
  37. const { token = '' } = store.getState().storeData.userInfo || {}
  38. // req.headers.Authorization = token
  39. req.headers.Token = token
  40. return req
  41. },
  42. (err) => {
  43. return Promise.reject(err)
  44. }
  45. )
  46. // 返回后拦截
  47. axios.interceptors.response.use(
  48. ({ data }): Promise<any> => {
  49. if (data.code !== 0) {
  50. message.error(data.message || data.msg)
  51. return Promise.reject(data)
  52. }
  53. return Promise.resolve(data)
  54. },
  55. (err) => {
  56. message.destroy()
  57. try {
  58. if (JSON.stringify(err).includes('401')) {
  59. clearAll()
  60. message.error({ title: '提示', content: 'Unauthorized' })
  61. return Promise.reject(err)
  62. }
  63. } catch (error) {
  64. clearAll()
  65. }
  66. message.error('网络异常')
  67. return Promise.reject(err)
  68. }
  69. )
  70. // post请求
  71. axios.post = (url: string, params?: object): Promise<any> =>
  72. axios({
  73. method: 'post',
  74. url,
  75. data: params
  76. })
  77. // get请求
  78. axios.get = (url: string, params?: object): Promise<any> =>
  79. axios({
  80. method: 'get',
  81. url,
  82. params
  83. })
  84. // put请求
  85. axios.put = (url: string, params?: object): Promise<any> =>
  86. axios({
  87. method: 'put',
  88. url,
  89. data: params
  90. })
  91. // delete请求
  92. axios.delete = (url: string, params?: object): Promise<any> =>
  93. axios({
  94. method: 'delete',
  95. url,
  96. data: params
  97. })
  98. export default axios