Home  >  Article  >  Web Front-end  >  What are the steps to set the request through axios global request parameters and return the interceptor?

What are the steps to set the request through axios global request parameters and return the interceptor?

亚连
亚连Original
2018-06-01 11:59:123255browse

Below I will share with you an article on axios global request parameter settings, request and return interceptor methods, which has a good reference value and I hope it will be helpful to everyone.

Application scenarios:

1. Each request carries parameters, such as token, timestamp, etc.

2, judge the returned status, such as whether the token has expired

The code is as follows:

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

The above is what I compiled for everyone, I hope It will be helpful to everyone in the future.

Related articles:

Sample code to implement image and file upload in vue

Simple example of Vue implementing search and news list functions

Methods of using axios in vue components

The above is the detailed content of What are the steps to set the request through axios global request parameters and return the interceptor?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn