index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import axios from 'axios'
  2. import Vue from 'vue'
  3. let config = {}
  4. const instance = axios.create(config)
  5. // 3. 配置信息
  6. config = {
  7. // 每次请求的协议、IP地址。 设置该配置后,每次请求路径都可以使用相对路径,例如"/admin/login"
  8. // baseURL: "http://127.0.0.1:5590",
  9. // 请求超时时间
  10. timeout: 0,
  11. // 每次请求携带cookie
  12. withCredentials: true
  13. }
  14. // 请求拦截,后期可能会用到,先注册在此
  15. instance.interceptors.request.use(
  16. function (config) {
  17. const token = localStorage.getItem('mobile_token')
  18. // let proxy_url = 'http://121.37.173.82:82'; //打包上线时请改用此处
  19. // let proxy_url = process.env.VUE_APP_BASE_URL; //打包上线时请改用此处
  20. // let proxy_url = '/proxy'//打包上线时此处请注释掉
  21. const proxyUrl = JSON.parse(localStorage.getItem('mobile_url'))
  22. config.url = proxyUrl + config.url
  23. // 在发送请求之前做些什么,例如加入token
  24. config.headers.Authorization = token
  25. config.headers['Content-Sign'] = 'b21779e9365ed84e4dd382ccdacc6d51'
  26. return config
  27. },
  28. function (error) {
  29. // 对请求错误做些什么
  30. return Promise.reject(error)
  31. }
  32. )
  33. // 2. 响应拦截
  34. instance.interceptors.response.use(
  35. (res) => {
  36. if (res.status === 200) {
  37. if (res.data.code === 200) {
  38. return res.data
  39. } else {
  40. // 若code 非 200
  41. if (res.data.code === 401) {
  42. localStorage.removeItem('mobile_token')
  43. return location.reload()
  44. }
  45. Vue.prototype.$Message.error(res.data.msg || '未知错误')
  46. return res.data || res
  47. }
  48. } else {
  49. return Vue.prototype.$Message.error('请求超时')
  50. }
  51. },
  52. // 对于错误响应的处理
  53. (err) => {
  54. Vue.prototype.$Notice.error({ title: '请求失败', desc: err })
  55. return err
  56. }
  57. )
  58. export default instance