request.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import axios from 'axios';
  2. import store from '@/store';
  3. import { Message } from 'element-ui';
  4. import { getToken } from '@/utils/auth';
  5. axios.defaults.withCredentials = true; // 跨域请求时是否需要使用凭证
  6. axios.defaults.dataType = 'json';
  7. axios.defaults.headers['cache-control'] = 'no-cache';
  8. axios.defaults.headers['Content-Type'] = 'application/json';
  9. axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest';
  10. const service = axios.create({
  11. baseURL: process.env.VUE_APP_BASE_API,
  12. // withCredentials: true, // 跨域请求时发送 cookies
  13. timeout: 10000
  14. });
  15. // 请求拦截器
  16. service.interceptors.request.use(
  17. config => {
  18. config.headers['Content-Type'] = 'application/json';
  19. return config;
  20. },
  21. error => {
  22. return Promise.reject(error);
  23. }
  24. );
  25. // 响应拦截器
  26. service.interceptors.response.use(
  27. response => {
  28. const res = response.data;
  29. if (res.code === 404) {
  30. Message({
  31. message: '请求的资源不存在',
  32. type: 'error',
  33. duration: 3 * 1000
  34. });
  35. return Promise.reject(new Error(res.message || 'Error'));
  36. }
  37. // 返回数据失败
  38. if (res.status === 0) {
  39. Message({
  40. message: res.error,
  41. type: 'error',
  42. duration: 3 * 1000
  43. });
  44. return Promise.reject(new Error(res.error || 'Error'));
  45. }
  46. // 无效的操作用户
  47. if (res.status === -1) {
  48. Message({
  49. message: res.error,
  50. type: 'error',
  51. duration: 3 * 1000
  52. });
  53. store.dispatch('user/resetSessionID').then(() => {
  54. window.location.href = '/';
  55. });
  56. return Promise.reject(new Error(res.error || 'Error'));
  57. }
  58. return res;
  59. },
  60. error => {
  61. Message({
  62. message: error.message,
  63. type: 'error',
  64. duration: 3 * 1000
  65. });
  66. return Promise.reject(error);
  67. }
  68. );
  69. /**
  70. * 得到必需的请求参数
  71. * @param {String} MethodName 请求方法名
  72. *
  73. * @returns {Object} 返回必需的请求参数
  74. * */
  75. export function getRequestParams(MethodName) {
  76. const { token, isHas } = getToken();
  77. return {
  78. MethodName,
  79. UserCode: isHas ? token.user_code : '',
  80. UserType: isHas ? token.user_type : '',
  81. SessionID: isHas ? token.session_id : ''
  82. };
  83. }
  84. export { service as request };