httpDice.js 2.3 KB

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