Home > Web Front-end > JS Tutorial > body text

How to set the global request parameters of axios

php中世界最好的语言
Release: 2018-03-28 14:16:20
Original
4184 people have browsed it

This time I will show you how to set the global request parameters of axios, what are the notes for setting the global request parameters of axios, the following is a practical case, let's take a look.

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)
})
Copy after login

I believe you have mastered it after reading the case in this article Method, for more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to publish the vue project through Baidu's BAE

Why axios http request cannot be used in vue2

The above is the detailed content of How to set the global request parameters of axios. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template