应用场景:
1,每个请求都带上的参数,比如 token,时间戳等
2,对返回的状态进行判断,比如 token 是否过期
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| axios.interceptors.request.use( config => { var xtoken = getXtoken(); if (xtoken != null) { config.headers["X-Token"] = xtoken; } if (config.method == "post") { config.data = { ...config.data, _t: Date.parse(new Date()) / 1000 }; } else if (config.method == "get") { config.params = { _t: Date.parse(new Date()) / 1000, ...config.params }; } return config; }, function(error) { return Promise.reject(error); } ); axios.interceptors.response.use( function(response) { if (response.data.code == 4) { localStorage.clear(); router.replace({ path: "/signin", query: { redirect: router.currentRoute.fullPath } }); } if (response.data.code == 5) { throw new Error(response.data.message); }
return response; }, function(error) { return Promise.reject(error); } );
|
使用 axios 拦截器取消请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var CancelToken = axios.CancelToken; var source = CancelToken.source();
axios.interceptors.request.use( function(config) { console.log(config); let dt = new Date(); let pd = intercept.createIntercept(store, config.name, dt.getTime()); if (pd === false) { config.cancelToken = source.token; source.cancel("Operation canceled by the user."); } return config; }, function(error) { return Promise.reject(error); } );
|
在向服务器发送前,修改请求数据,使用transformRequest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <script> import axios from 'axios' import qs from 'qs'
let http = axios.create({ baseURL: 'https://www.easy-mock.com/mock/5d41580a1a802c0d5e53dcc2/example/',
transformRequest: [function (data) { data.sex = 'man' return qs.stringify(data) }],
headers: {'content-type': 'application/x-www-form-urlencoded'}, }) export default { name: "create_transformRequest", methods: { postUrl () { http.post('bb', { 'name': 'xiaoming', 'age': 12 }) } }, created () { this.postUrl() } } </script>
|
参考:vue axios 请求拦截器,取消