request.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import axios from 'axios'
  2. import Cookies from 'js-cookie'
  3. import router from '@/router'
  4. import qs from 'qs'
  5. import { clearLoginInfo } from '@/utils'
  6. import isPlainObject from 'lodash/isPlainObject'
  7. import {MessageBox} from "element-ui";
  8. const http = axios.create({
  9. baseURL: window.SITE_CONFIG['apiURL'],
  10. timeout: 1000 * 180,
  11. withCredentials: true
  12. })
  13. /**
  14. * 请求拦截
  15. */
  16. http.interceptors.request.use(config => {
  17. // 临时免登陆
  18. // Cookies.set('token', '49e42af404cbb94096920626f01fb6f6')
  19. config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  20. config.headers['sessionToken'] = Cookies.get('token') || ''
  21. // 默认参数
  22. var defaults = {}
  23. // 防止缓存,GET请求默认带_t参数
  24. if (config.method === 'get') {
  25. config.params = {
  26. ...config.params,
  27. ...{ '_t': new Date().getTime() }
  28. }
  29. }
  30. if (isPlainObject(config.params)) {
  31. config.params = {
  32. ...defaults,
  33. ...config.params
  34. }
  35. }
  36. if (isPlainObject(config.data)) {
  37. config.data = {
  38. ...defaults,
  39. ...config.data
  40. }
  41. if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
  42. config.data = qs.stringify(config.data)
  43. }
  44. }
  45. return config
  46. }, error => {
  47. return Promise.reject(error)
  48. })
  49. /**
  50. * 响应拦截
  51. */
  52. http.interceptors.response.use(response => {
  53. if (response.data.code === 401 || response.data.code === 402 || response.data.code === 403 || response.data.code === 10001) {
  54. if(localStorage.getItem('pathCopy')) {
  55. localStorage.setItem('pathCopyshow',true)
  56. }
  57. clearLoginInfo()
  58. MessageBox.confirm(response.data.msg, '提示',{
  59. showClose: false,
  60. showCancelButton: false,
  61. callback: () => {
  62. router.replace({ name: 'login' })
  63. }
  64. })
  65. return Promise.reject(response.data.msg)
  66. }
  67. return response
  68. }, error => {
  69. console.error(error)
  70. return Promise.reject(error)
  71. })
  72. export default http