应用场景:
1,每个请求都带上的参数,比如token,时间戳等。
2,对返回的状态进行判断,比如token是否过期
代码如下:
[javascript] view plain copy
- 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) {
- // token 已过期,重定向到登录页面
- if (response.data.code == 4){
- localStorage.clear()
- router.replace({
- path: '/signin',
- query: {redirect: router.currentRoute.fullPath}
- })
- }
- return response
- }, function (error) {
- // Do something with response error
- return Promise.reject(error)
- })