银讯财经网
您的当前位置:首页怎么设置axios的全局请求参数

怎么设置axios的全局请求参数

来源:银讯财经网


这次给大家带来怎么设置axios的全局请求参数,设置axios全局请求参数的注意事项有哪些,下面就是实战案例,一起来看一下。

应用场景:

1,每个请求都带上的参数,比如token,时间戳等。

2,对返回的状态进行判断,比如token是否过期

代码如下:

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)
})

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

vue项目怎样通过百度的BAE发布

为什么vue2中不能使用axios http请求

显示全文