首頁  >  文章  >  web前端  >  透過axios全域請求參數設定請求以及返回攔截器操作步驟有哪些?

透過axios全域請求參數設定請求以及返回攔截器操作步驟有哪些?

亚连
亚连原創
2018-06-01 11:59:123171瀏覽

下面我就為大家分享一篇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)
})

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

vue中實作圖片和檔案上傳的範例程式碼

Vue實作搜尋和新聞清單功能簡單範例

在vue元件中使用axios的方法

以上是透過axios全域請求參數設定請求以及返回攔截器操作步驟有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn