axios.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {
  2. Message
  3. } from 'element-ui';
  4. import config from '~/config/app'
  5. function checkParams(params) {
  6. if (typeof params != 'object') return params
  7. for (let key in params) {
  8. const value = params[key];
  9. if (value === null || value === undefined || value === "") {
  10. delete params[key];
  11. }
  12. }
  13. return params;
  14. }
  15. export default function({
  16. $axios,
  17. redirect,
  18. store
  19. }, inject) {
  20. $axios.setBaseURL(config.baseUrl + '/api/v1')
  21. $axios.onRequest(config => {
  22. config.data = checkParams(config.data)
  23. config.params = checkParams(config.params)
  24. if (config.method == 'GET') {
  25. config.url += paramsToStr(config.params)
  26. }
  27. config.headers.token = store.state.token
  28. // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  29. })
  30. $axios.onResponse((response) => {
  31. const {
  32. code,
  33. show,
  34. msg
  35. } = response.data;
  36. if (code == 0 && show && msg) {
  37. Message({
  38. message: msg,
  39. type: 'error'
  40. })
  41. } else if (code == -1) {
  42. console.log(response.data)
  43. store.commit('logout')
  44. //todo 测试关闭登录
  45. redirect('/account/login')
  46. }
  47. })
  48. $axios.onError(error => {
  49. Message({
  50. message: '系统错误',
  51. type: 'error'
  52. })
  53. })
  54. inject('get', $axios.$get)
  55. inject('post', $axios.$post)
  56. }