request.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import axios from 'axios'
  2. import { Message, MessageBox } from 'element-ui'
  3. import store from '../store'
  4. import { getToken } from '@/utils/auth'
  5. import cleanDeep from 'clean-deep'
  6. import qs from 'qs'
  7. // 创建axios实例
  8. const service = axios.create({
  9. baseURL: process.env.BASE_API, // api的base_url
  10. timeout: 30000 // 请求超时时间
  11. })
  12. // request拦截器
  13. service.interceptors.request.use(config => {
  14. let tocken =getToken()
  15. if (tocken) {
  16. config.headers['Authorization'] = tocken // 让每个请求携带自定义token 请根据实际情况自行修改
  17. }
  18. if(config.url.indexOf('/api-mall-admin')== -1){
  19. if(config.url.indexOf('/api-web')== -1 && config.url.indexOf('/api-auth')== -1){
  20. config.url = '/api-mall-admin'+config.url
  21. }
  22. }
  23. // 是否进行数据过滤
  24. const noCleanDeep = config.noCleanDeep || false
  25. if (config.requestType === 'form') {
  26. config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  27. config.data = qs.stringify(
  28. noCleanDeep ? config.data : cleanDeep(config.data)
  29. )
  30. } else if (config.requestType === 'multipart') {
  31. config.headers['Content-Type'] = 'multipart/form-data'
  32. } else {
  33. config.data = noCleanDeep ? config.data : cleanDeep(config.data)
  34. }
  35. config.params = noCleanDeep
  36. ? qs.stringify(config.data)
  37. : cleanDeep(config.params)
  38. return config
  39. }, error => {
  40. // Do something with request error// for debug
  41. Promise.reject(error)
  42. })
  43. // respone拦截器
  44. service.interceptors.response.use(
  45. response => {
  46. /**
  47. * code为非200是抛错 可结合自己业务进行修改
  48. */
  49. const res = response.data
  50. if (res.code !== 200) {
  51. Message({
  52. message: res.msg||res.message,
  53. type: 'error',
  54. duration: 3 * 1000
  55. })
  56. // 401:未登录;
  57. if (res.code === 401 || res.code === 403) {
  58. location = window.location.origin;
  59. console.log('401/403',location)
  60. // MessageBox.confirm('登录过期请重新登录', '确定登出', {
  61. // confirmButtonText: '重新登录',
  62. // cancelButtonText: '取消',
  63. // type: 'warning'
  64. // }).then(() => {
  65. // store.dispatch('FedLogOut').then(() => {
  66. // location.reload()// 为了重新实例化vue-router对象 避免bug
  67. // location.href = window.location.hostname;
  68. // })
  69. // })
  70. }
  71. return Promise.reject('error')
  72. } else {
  73. return response.data
  74. }
  75. },
  76. error => {
  77. console.log('err' + error)// for debug
  78. Message({
  79. message: error.message,
  80. type: 'error',
  81. duration: 3 * 1000
  82. })
  83. return Promise.reject(error)
  84. }
  85. )
  86. export default service