ajax.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import { Toast } from 'vant'
  4. // 配置api地址
  5. // axios设置
  6. const $ajax = axios.create({
  7. baseURL: process.env.VUE_APP_BASE_API,
  8. timeout: 6000,
  9. withCredentials: true
  10. })
  11. /* 拦截器 */
  12. $ajax.interceptors.request.use(config => {
  13. // 在请求发送之前做一些事
  14. // console.log('--发送之前--', config)
  15. if (config.method === 'post' || config.method === 'POST') {
  16. if (typeof config.data !== 'string') {
  17. config.data = qs.stringify(config.data)
  18. }
  19. }
  20. // 获取插入token
  21. return config
  22. }, function (error) {
  23. // 当出现请求错误是做一些事
  24. console.log('--请求超时--', error)
  25. Toast('请求超时,请重试')
  26. return Promise.reject(error)
  27. })
  28. // 添加一个返回拦截器
  29. $ajax.interceptors.response.use((response) => {
  30. // 是否需要toast弹窗
  31. if (response.config.headers.noToast !== 1) {
  32. // 判断是否需要重新登录
  33. if (response.data.error_msg === '需要登录' || response.data.error_code === 1001) {
  34. Toast({
  35. message: '需要登录',
  36. forbidClick: true,
  37. duration: 1500
  38. })
  39. }
  40. if (response.data.error_code && response.data.error_code !== 0) {
  41. Toast({
  42. message: response.data.error_msg || '请求失败,请重试',
  43. forbidClick: true,
  44. duration: 1500
  45. })
  46. }
  47. }
  48. return response
  49. }, function (error) {
  50. console.log('--响应超时--', error)
  51. Toast('响应超时,请重试')
  52. return Promise.reject(error)
  53. })
  54. export default $ajax