request.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import axios from 'axios'
  2. import { MessageBox, Message,Notification} from 'element-ui'
  3. import store from '@/store'
  4. import { getToken, getSign } from '@/utils/auth'
  5. import { randomStr20 } from '@/utils/util'
  6. import errorCode from '@/utils/errorCode'
  7. //import md5 from 'js-md5'
  8. //const md5key = "3Jr8S1K18rcC1wAfv8";
  9. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  10. // 创建axios实例
  11. const service = axios.create({
  12. // axios中请求配置有baseURL选项,表示请求URL公共部分
  13. baseURL: process.env.VUE_APP_BASE_API,
  14. // 超时
  15. timeout: 30000
  16. })
  17. // request拦截器
  18. service.interceptors.request.use(config => {
  19. //// console.log("service.interceptors.request config = ==========================================================="+JSON.stringify(config))
  20. // 是否需要设置 token
  21. const isToken = (config.headers || {}).isToken === false
  22. let timestamp = parseInt(new Date().getTime()), nonce = randomStr20();
  23. if (getToken() && !isToken) {
  24. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  25. }
  26. config.headers['x-zz-timestamp'] = timestamp
  27. // post请求映射data参数
  28. // // console.log("config.method = " +config.method +" ,config = "+JSON.stringify(config))
  29. if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
  30. var params = config.data || {};
  31. //// console.log("config.data == "+JSON.stringify(params))
  32. //let signStr = JSON.stringify(params) + "nonce" + timestamp + "" + md5key;
  33. var sign = getSign(params, timestamp);
  34. var urlParams = config.urlParams || '';
  35. let url = config.url + '?' + urlParams + 'sign=' + sign + '&nonce=' + nonce;
  36. config.url = url;
  37. }
  38. // get请求映射params参数
  39. else if (config.method === 'get') {
  40. var params = config.params || {};
  41. // let signStr = JSON.stringify(config.params) + "nonce" + timestamp + "" + md5key;
  42. // var sign = md5(signStr);
  43. var sign = getSign(params, timestamp)
  44. //let url = config.url + '?';
  45. let url = config.url + '?sign=' + sign + '&nonce=' + nonce + '&';
  46. for (const propName of Object.keys(params)) {
  47. const value = config.params[propName];
  48. var part = encodeURIComponent(propName) + "=";
  49. if (value !== null && typeof(value) !== "undefined") {
  50. if (typeof value === 'object') {
  51. for (const key of Object.keys(value)) {
  52. if (value[key] !== null && typeof (value[key]) !== 'undefined') {
  53. let params = propName + '[' + key + ']';
  54. let subPart = encodeURIComponent(params) + '=';
  55. url += subPart + encodeURIComponent(value[key]) + '&';
  56. }
  57. }
  58. } else {
  59. url += part + encodeURIComponent(value) + "&";
  60. }
  61. }
  62. }
  63. url = url.slice(0, -1);
  64. config.params = {};
  65. config.url = url;
  66. }
  67. return config
  68. }, error => {
  69. // console.log(error)
  70. Promise.reject(error)
  71. })
  72. // 响应拦截器
  73. service.interceptors.response.use(res => {
  74. // 未设置状态码则默认成功状态
  75. const code = res.data.code || 0;
  76. // console.log("code == " +code)
  77. // 获取错误信息
  78. const msg = errorCode[code] || res.data.msg || errorCode['default']
  79. if (code === 401) {
  80. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  81. confirmButtonText: '重新登录',
  82. cancelButtonText: '取消',
  83. type: 'warning'
  84. }
  85. ).then(() => {
  86. store.dispatch('LogOut').then(() => {
  87. location.href = '/index';
  88. })
  89. }).catch(() => {});
  90. return Promise.reject('令牌验证失败')
  91. } else if (code === 500) {
  92. Message({
  93. message: msg,
  94. type: 'error'
  95. })
  96. return Promise.reject(new Error(msg))
  97. } else if (code != 0) {
  98. // console.log("<<<<<<<<<<<<<<<<<<<<<<<<<<+"+code);
  99. Message({
  100. message: msg,
  101. type: 'error'
  102. })
  103. /*
  104. Message({
  105. message: msg,
  106. type: 'error'
  107. })*/
  108. return Promise.reject('error')
  109. } else {
  110. return res.data
  111. }
  112. },
  113. error => {
  114. // console.log('err' + error)
  115. let { message } = error;
  116. if (message == "Network Error") {
  117. message = "后端接口连接异常";
  118. }
  119. else if (message.includes("timeout")) {
  120. message = "系统接口请求超时";
  121. }
  122. else if (message.includes("Request failed with status code")) {
  123. message = "系统接口" + message.substr(message.length - 3) + "异常";
  124. }
  125. Message({
  126. message: message,
  127. type: 'error',
  128. duration: 5 * 1000
  129. })
  130. return Promise.reject(error)
  131. }
  132. )
  133. export default service