service.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. const service = axios.create({
  8. baseURL: window.SITE_CONFIG['apiURL1'],
  9. timeout: 1000 * 180,
  10. withCredentials: true
  11. })
  12. /**
  13. * 请求拦截
  14. */
  15. service.interceptors.request.use(config => {
  16. config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  17. config.headers['token'] = Cookies.get('token') || ''
  18. // 默认参数
  19. var defaults = {}
  20. // 防止缓存,GET请求默认带_t参数
  21. if (config.method === 'get') {
  22. config.params = {
  23. ...config.params,
  24. ...{ '_t': new Date().getTime() }
  25. }
  26. }
  27. if (isPlainObject(config.params)) {
  28. config.params = {
  29. ...defaults,
  30. ...config.params
  31. }
  32. }
  33. if (isPlainObject(config.data)) {
  34. config.data = {
  35. ...defaults,
  36. ...config.data
  37. }
  38. if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
  39. config.data = qs.stringify(config.data)
  40. }
  41. }
  42. return config
  43. }, error => {
  44. return Promise.reject(error)
  45. })
  46. /**
  47. * 响应拦截
  48. */
  49. service.interceptors.response.use(response => {
  50. if (response.data.code === 401 || response.data.code === 10001) {
  51. clearLoginInfo()
  52. router.replace({ name: 'login' })
  53. return Promise.reject(response.data.msg)
  54. }
  55. return response
  56. }, error => {
  57. return Promise.reject(error)
  58. })
  59. export default service