当前位置:   article > 正文

Vue2中axios封装(超级详细,拿到手直接用)_vue2 axios封装

vue2 axios封装

封装的axios.js文件

  1. /**
  2. * 全站http配置
  3. *
  4. * axios参数说明
  5. * isSerialize是否开启form表单提交
  6. * isToken是否需要token
  7. */
  8. import axios from 'axios';
  9. import store from '@/store/';
  10. import router from '@/router/router';
  11. import {serialize} from '@/util/util';
  12. import {getToken} from '@/util/auth';
  13. import {Message} from 'element-ui';
  14. import website from '@/config/website';
  15. import {Base64} from 'js-base64';
  16. import NProgress from 'nprogress';
  17. import 'nprogress/nprogress.css';
  18. //默认超时时间
  19. axios.defaults.timeout = 120000;
  20. //返回其他状态码
  21. axios.defaults.validateStatus = function (status) {
  22. return status >= 200 && status <= 500;
  23. };
  24. //跨域请求,允许保存cookie
  25. // axios.defaults.withCredentials = true;
  26. // NProgress 配置
  27. NProgress.configure({
  28. showSpinner: false
  29. });
  30. //http request拦截
  31. axios.interceptors.request.use(config => {
  32. //开启 progress bar
  33. // NProgress.start();
  34. const meta = (config.meta || {});
  35. const isToken = meta.isToken === false;
  36. config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  37. //让每个请求携带token
  38. if (getToken() && !isToken) {
  39. config.headers[website.tokenHeader] = 'bearer ' + getToken()
  40. }
  41. //headers中配置text请求
  42. if (config.text === true) {
  43. config.headers["Content-Type"] = "text/plain";
  44. }
  45. //headers中配置serialize为true开启序列化
  46. if (config.method === 'post' && meta.isSerialize === true) {
  47. config.data = serialize(config.data);
  48. }
  49. return config
  50. }, error => {
  51. return Promise.reject(error)
  52. });
  53. //http response 拦截
  54. axios.interceptors.response.use(res => {
  55. //关闭 progress bar
  56. // NProgress.done();
  57. //获取状态码
  58. const status = res.status;
  59. const statusWhiteList = website.statusWhiteList || [];
  60. const message = res.data.msg || res.data.error_description || '未知错误';
  61. //如果在白名单里则自行catch逻辑处理
  62. if (statusWhiteList.includes(status)) return Promise.reject(res);
  63. //如果是401则跳转到登录页面
  64. if (status === 401) {
  65. router.replace({path: '/login'});
  66. }
  67. // 如果请求为非200否者默认统一处理
  68. if (status !== 200 && status !== 401) {
  69. Message({
  70. message: message,
  71. type: 'error'
  72. });
  73. return Promise.reject(new Error(message))
  74. }
  75. // if(status === 401){
  76. // Message.closeAll()
  77. // Message({
  78. // showClose: true,
  79. // message: message,
  80. // type: 'error'
  81. // });
  82. // }
  83. return res;
  84. }, error => {
  85. // NProgress.done();
  86. if(error.message.includes('timeout')){
  87. Message({
  88. message: '网络响应过慢,请刷新重试!',
  89. type: 'error'
  90. });
  91. return Promise.reject(new Error(error));
  92. } else {
  93. return Promise.reject(new Error(error));
  94. }
  95. });
  96. export default axios;

2.serialize方法如下:

  1. export const serialize = data => {
  2. let list = [];
  3. Object.keys(data).forEach(ele => {
  4. list.push(`${ele}=${data[ele]}`)
  5. })
  6. return list.join('&');
  7. };

3.getToken方法如下:

  1. import Cookies from 'js-cookie'
  2. const TokenKey = 'saber-access-token'
  3. const RefreshTokenKey = 'saber-refresh-token'
  4. export function getToken() {
  5. return Cookies.get(TokenKey)
  6. }

好啦,这就封装好了,去使用吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/1001473
推荐阅读
相关标签
  

闽ICP备14008679号