http.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import axios from 'axios'
  2. import Qs from 'qs'
  3. import { MessageBox } from 'element-ui'
  4. import { Cookie } from '../util/util'
  5. import $store from '@/store'
  6. let host = ''
  7. if (window.location.port === '8080') {
  8. host = '//test-k3.eosget.io'
  9. }
  10. let ax = axios.create({
  11. baseURL: host,
  12. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  13. transformRequest: [function (data) {
  14. data = Qs.stringify(data)
  15. return data
  16. }],
  17. transformResponse: [],
  18. withCredentials: true
  19. })
  20. ax.interceptors.request.use(
  21. config => {
  22. // 添加登陆态
  23. if (config.needLogin) {
  24. if ($store.state.account === 'NO_LOGINING') {
  25. $store.dispatch('doScatterLogin').then((account) => {
  26. return handleConfig(config)
  27. })
  28. } else {
  29. return handleConfig(config)
  30. }
  31. } else {
  32. return config
  33. }
  34. },
  35. error => {
  36. return Promise.reject(error)
  37. }
  38. )
  39. // 拦截器处理错误
  40. ax.interceptors.response.use(
  41. async response => {
  42. if (response.data.result === 1 || response.data.code === -90001) { // result为1时请求成功
  43. return Promise.resolve(response)
  44. } else {
  45. if (response.data.code === -5) { // code为-5是登录态失效
  46. try {
  47. await $store.dispatch('doGameLogin')
  48. return Promise.resolve(response)
  49. } catch (error) {
  50. return Promise.reject(new Error(error))
  51. }
  52. } else {
  53. // 请求出错提示错误
  54. MessageBox.confirm(response.data.msg, 'Error', {
  55. center: true,
  56. showCancelButton: false,
  57. showConfirmButton: false,
  58. callback () {}
  59. })
  60. return Promise.reject(new Error(response.data.msg))
  61. }
  62. }
  63. },
  64. error => {
  65. return Promise.reject(error)
  66. }
  67. )
  68. function handleConfig (config) {
  69. let authData = {
  70. account: Cookie.getCookie('account') || $store.state.account.name,
  71. player: Cookie.getCookie('account') || $store.state.account.name,
  72. token: Cookie.getCookie('token') || ''
  73. }
  74. if (config.method === 'post') {
  75. config.data = Object.assign(config.data, authData)
  76. } else if (config.method === 'get') {
  77. config.params = Object.assign(config.params, authData)
  78. }
  79. return config
  80. }
  81. export default ax