request.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import axios from 'axios'
  2. import { Notification, MessageBox, Message } from 'element-ui'
  3. import store from '../store'
  4. import errorCode from '../js/errorCode'
  5. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  6. // 创建axios实例
  7. const service = axios.create({
  8. // axios中请求配置有baseURL选项,表示请求URL公共部分
  9. baseURL:process.env.BASE_URL,
  10. // baseURL:"/api",
  11. // 超时
  12. timeout: 10000
  13. })
  14. // request拦截器
  15. service.interceptors.request.use(config => {
  16. // 是否需要设置 token
  17. // const isToken = (config.headers || {}).isToken === false
  18. // if (getToken() && !isToken) {
  19. // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  20. // }
  21. return config
  22. }, error => {
  23. console.log(error)
  24. Promise.reject(error)
  25. })
  26. // 响应拦截器
  27. service.interceptors.response.use(res => {
  28. // 未设置状态码则默认成功状态
  29. const code = res.data.code || 200;
  30. // 获取错误信息
  31. const msg = errorCode[code] || res.data.msg || errorCode['default']
  32. if (code === 401) {
  33. console.log("zxc")
  34. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  35. confirmButtonText: '重新登录',
  36. cancelButtonText: '取消',
  37. type: 'warning'
  38. }
  39. ).then(() => {
  40. // store.dispatch('LogOut').then(() => {
  41. // location.href = '/index';
  42. // })
  43. })
  44. } else if (code === 500) {
  45. Message({
  46. message: msg,
  47. type: 'error'
  48. })
  49. return Promise.reject(new Error(msg))
  50. } else if (code !== 200) {
  51. Notification.error({
  52. title: msg
  53. })
  54. return Promise.reject('error')
  55. } else {
  56. return res.data
  57. }
  58. },
  59. error => {
  60. console.log('err' + error)
  61. let { message } = error;
  62. if (message == "Network Error") {
  63. message = "后端接口连接异常";
  64. }
  65. else if (message.includes("timeout")) {
  66. message = "系统接口请求超时";
  67. }
  68. else if (message.includes("Request failed with status code")) {
  69. message = "系统接口" + message.substr(message.length - 3) + "异常";
  70. }
  71. Message({
  72. message: message,
  73. type: 'error',
  74. duration: 5 * 1000
  75. })
  76. return Promise.reject(error)
  77. }
  78. )
  79. export default service