api.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import axios from 'axios'
  2. import { ElMessage } from 'element-plus'
  3. import { ROOTPATH } from './httpUrl'
  4. const apiClient = axios.create({
  5. baseURL: ROOTPATH,
  6. timeout: 10000
  7. })
  8. // 请求拦截器
  9. apiClient.interceptors.request.use(
  10. config => {
  11. if (config.type === 'json') {
  12. config.headers['Content-Type'] = 'application/json'
  13. } else {
  14. config.headers['Content-Type'] = 'multipart/form-data'
  15. }
  16. // token
  17. const token = localStorage.getItem('token')
  18. if (token) {
  19. config.headers['token'] = token
  20. }
  21. return config
  22. },
  23. error => {
  24. return Promise.reject(error)
  25. }
  26. )
  27. // 响应拦截器
  28. apiClient.interceptors.response.use(
  29. response => {
  30. const res = response.data
  31. // ✅ 判断业务状态码
  32. if (res.code !== 0) {
  33. // 弹出提示信息
  34. ElMessage({
  35. message: res.msg || '请求失败',
  36. type: 'warning',
  37. duration: 2000
  38. })
  39. }
  40. // 无论成功失败都返回,方便前端继续逻辑判断
  41. return res
  42. },
  43. error => {
  44. // 网络错误、超时、服务器错误时
  45. ElMessage({
  46. message: error.message || '网络错误,请稍后再试',
  47. type: 'error',
  48. duration: 2000
  49. })
  50. return Promise.reject(error)
  51. }
  52. )
  53. export default apiClient