axios 設置攔截器 全局設置帶默認參數(發送 token 等)


應用場景:

1,每個請求都帶上的參數,比如token,時間戳等。

2,對返回的狀態進行判斷,比如token是否過期

代碼如下:

[javascript] view plain copy

  1. axios.interceptors.request.use( 
  2.         config => { 
  3. var xtoken = getXtoken() 
  4. if(xtoken != null){ 
  5.                 config.headers['X-Token'] = xtoken 
  6.             } 
  7. if(config.method=='post'){ 
  8.                 config.data = { 
  9.                     ...config.data, 
  10.                     _t: Date.parse(new Date())/1000, 
  11.                 } 
  12.             }else if(config.method=='get'){ 
  13.                 config.params = { 
  14.                     _t: Date.parse(new Date())/1000, 
  15.                     ...config.params 
  16.                 } 
  17.             } 
  18. return config 
  19.         },function(error){ 
  20. return Promise.reject(error) 
  21.         } 
  22.     ) 
  23. axios.interceptors.response.use(function (response) { 
  24. // token 已過期,重定向到登錄頁面
  25. if (response.data.code == 4){ 
  26.         localStorage.clear() 
  27.         router.replace({ 
  28.                         path: '/signin', 
  29.                         query: {redirect: router.currentRoute.fullPath} 
  30.                     }) 
  31.     } 
  32. return response 
  33. }, function (error) { 
  34. // Do something with response error
  35. return Promise.reject(error) 
  36. }) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM