【前端】智能库房综合管理系统前端项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.7 KiB

3 years ago
3 years ago
3 years ago
  1. import axios from 'axios'
  2. import router from '@/router/routers'
  3. import { Notification } from 'element-ui'
  4. import store from '../store'
  5. import { getToken } from '@/utils/auth'
  6. import Config from '@/settings'
  7. import Cookies from 'js-cookie'
  8. // 创建axios实例
  9. const service = axios.create({
  10. baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/', // api 的 base_url
  11. // baseURL: process.env.NODE_ENV === 'production' ? 'http://192.168.99.84:7070' : '/', // api 的 base_url
  12. timeout: Config.timeout // 请求超时时间
  13. })
  14. // request拦截器
  15. service.interceptors.request.use(
  16. config => {
  17. if (getToken()) {
  18. config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  19. }
  20. config.headers['Content-Type'] = 'application/json'
  21. return config
  22. },
  23. error => {
  24. Promise.reject(error)
  25. }
  26. )
  27. // response 拦截器
  28. service.interceptors.response.use(
  29. response => {
  30. // return response.data
  31. const errorMsg = response.data.message
  32. if (response.data.code === 200) {
  33. return response.data.data
  34. } else {
  35. Notification.error({
  36. title: errorMsg,
  37. duration: 5000
  38. })
  39. }
  40. },
  41. error => {
  42. // 兼容blob下载出错json提示
  43. if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
  44. const reader = new FileReader()
  45. reader.readAsText(error.response.data, 'utf-8')
  46. reader.onload = function(e) {
  47. const errorMsg = JSON.parse(reader.result).message
  48. Notification.error({
  49. title: errorMsg,
  50. duration: 5000
  51. })
  52. }
  53. } else {
  54. let code = 0
  55. try {
  56. code = error.response.data.status
  57. } catch (e) {
  58. if (error.toString().indexOf('Error: timeout') !== -1) {
  59. Notification.error({
  60. title: '网络请求超时',
  61. duration: 5000
  62. })
  63. return Promise.reject(error)
  64. }
  65. }
  66. console.log(code)
  67. if (code) {
  68. if (code === 401) {
  69. store.dispatch('LogOut').then(() => {
  70. // 用户登录界面提示
  71. Cookies.set('point', 401)
  72. location.reload()
  73. })
  74. } else if (code === 403) {
  75. router.push({ path: '/401' })
  76. } else {
  77. const errorMsg = error.response.data.message
  78. if (errorMsg !== undefined) {
  79. Notification.error({
  80. title: errorMsg,
  81. duration: 5000
  82. })
  83. }
  84. }
  85. } else {
  86. Notification.error({
  87. title: '接口请求失败',
  88. duration: 5000
  89. })
  90. }
  91. }
  92. return Promise.reject(error)
  93. }
  94. )
  95. export default service