调试vuex

封装axios

yarn add axios

  1. import axios from 'axios'
  2. import store from '@/store'
  3. import router from '@/router'
  4. // baseURL设置/超时时间设置
  5. const instance = axios.create({
  6. baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  7. timeout: 5000
  8. })
  9. // 添加请求拦截器
  10. instance.interceptors.request.use(function (config) {
  11. // 1. 获取token
  12. const { token } = store.state.user.profile
  13. // 2. 请求头设置token
  14. if (token) {
  15. config.headers.Authorization = `Bearer ${token}`
  16. }
  17. return config
  18. }, function (error) {
  19. // 对请求错误做些什么
  20. return Promise.reject(error)
  21. })
  22. // 添加响应拦截器
  23. instance.interceptors.response.use(function (response) {
  24. return response.data
  25. }, function (error) {
  26. // 对响应错误做点什么
  27. if (error.response && error.response.status === 401) {
  28. const redirectUrl = encodeURIComponent(router.currentRoute.value.fullPath)
  29. router.push('/login?redirectUrl=' + redirectUrl)
  30. }
  31. return Promise.reject(error)
  32. })
  33. /**
  34. * @param {String} - url 请求地址
  35. * @param {String} - method 请求类型
  36. * @param {Object} - submitData 对象类型,提交数据
  37. */
  38. const request = (url, method, submitData) => {
  39. return instance({
  40. url,
  41. method,
  42. [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  43. })
  44. }
  45. export default request