生活随笔
收集整理的這篇文章主要介紹了
axios 设置拦截器 全局设置带默认参数(发送 token 等)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
應用場景:
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)? })?
轉載于:https://www.cnblogs.com/mouseleo/p/8262421.html
總結
以上是生活随笔為你收集整理的axios 设置拦截器 全局设置带默认参数(发送 token 等)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。