request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import axios from 'axios'
  2. import { MessageBox, Message } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. import qs from 'qs'
  6. import SYSTEM_EVN from '../../config/evn'
  7. // 创建axios实例
  8. const service = axios.create({
  9. baseURL: SYSTEM_EVN.BASE_URL
  10. // baseURL: 'http://getway.vipgz4.idcfengye.com'
  11. // withCredentials: true, // 跨域请求时发送cookiesokies
  12. // timeout: 30000 // 请求超时
  13. })
  14. // 请求拦截器
  15. service.interceptors.request.use(
  16. config => {
  17. if (config.method === 'post' && config.url === '/auth/oauth/login?project=8030') { // 请求为post 使用qs转换数据
  18. config.data = qs.stringify(config.data)
  19. config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  20. } else {
  21. config.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
  22. }
  23. // 在发出请求前做点什么
  24. if (store.getters.token) {
  25. config.headers['Authorization'] = 'bearer ' + getToken()
  26. }
  27. return config
  28. },
  29. error => {
  30. // 处理请求错误
  31. console.log(error)
  32. return Promise.reject(error)
  33. }
  34. )
  35. // 响应拦截器
  36. service.interceptors.response.use(
  37. /**
  38. * 如果您想要获取诸如头或状态之类的http信息
  39. * return response => response
  40. */
  41. /**
  42. * 通过自定义代码确定请求状态
  43. */
  44. response => {
  45. const res = response.data
  46. // 如果自定义代码不是1,则判断为错误。
  47. if (res.success) {
  48. return res
  49. } else {
  50. if (res.code !== 1) {
  51. Message({
  52. message: res.message || 'Error',
  53. type: 'error',
  54. duration: 5 * 1000
  55. })
  56. // 50008:非法令牌;50012:其他客户端登录;50014:令牌过期; 暂时没用
  57. if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  58. // to re-login
  59. MessageBox.confirm('您已注销,您可以取消以停留在此页,或重新登录', '确认注销', {
  60. confirmButtonText: '确定',
  61. cancelButtonText: '取消',
  62. type: 'warning'
  63. }).then(() => {
  64. store.dispatch('user/resetToken').then(() => {
  65. location.reload()
  66. })
  67. })
  68. }
  69. return Promise.reject(new Error(res.message || 'Error'))
  70. } else {
  71. return res
  72. }
  73. }
  74. },
  75. error => {
  76. console.log('err' + error)
  77. Message({
  78. message: error.message,
  79. type: 'error',
  80. duration: 3 * 1000
  81. })
  82. return Promise.reject(error)
  83. }
  84. )
  85. export default service