Vue 攔截器的使用


攔截器

可以全局進行攔截器設置。攔截器在發送請求前或響應返回時做一些特殊的處理。

攔截器的注冊

Vue.http.interceptors.push({ request: function ( request ) { // 更改請求類型為POST request.method = 'POST'; return request; }, response: function ( response ) { // 修改返回數據 response.data = [{ custom: 'custom' }]; return response; } });

工廠函數注冊

Vue.http.interceptors.push(function () { return { request: function ( request ) { return request; }, response: function ( response ) { return response; } } });

Vue.http.interceptors.push(function ( request, next ) { // 請求發送前的處理邏輯 next(function () { // 請求發送后的處理邏輯 // 更具請求的狀態, response參數會返回給 successCallback或errorCallback return response }); });

實現的功能:

  • AJAX請求的loading界面

Vue.http.interceptors.push((request, next) => { // 通過控制 組件的`v-show`值顯示loading組件 loading.show = true; next((response) => { loading.show = false return response }); });
  • 請求失敗時的提示對話框

vue-resource 攔截器使用
在vue項目使用vue-resource的過程中,臨時增加了一個需求,需要在任何一個頁面任何一次http請求,增加對token過期的判斷,如果token已過期,需要跳轉至登錄頁面。如果要在每個頁面中的http請求操作中添加一次判斷,那么會是一個非常大的修改工作量。
vue-resource的interceptors攔截器的作用正是解決此需求的妙方。在每次http的請求響應之后,如果設置了攔截器如下,會優先執行攔截器函數,獲取響應體,然后才會決定是否把response返回給then進行接收。那么我們可以在這個攔截器里邊添加對響應狀態碼的判斷,來決定是跳轉到登錄頁面還是留在當前頁面繼續獲取數據。

main.js里面設置:
Vue.http.interceptors.push((request, next) => { 
 console.log(this)//此處this為請求所在頁面的Vue實例 
 // modify request 
 request.method = 'POST';//在請求之前可以進行一些預處理和配置 
  
 // continue to next interceptor 
  next((response) => {//在響應之后傳給then之前對response進行修改和邏輯判斷。對於token時候已過期的判斷,就添加在此處,頁面中任何一次http請求都會先調用此處方法 
  
    response.body = '...'; 
    return response; 
  
 }); 
});
Vue.http.interceptors.push((request, next) =>{ 
 //登錄成功后將后台返回的toekn在本地存下來,每次請求從sessionStorage中拿到存儲的token值 
 let token=sessionStorage.getItem('STORAGE_TOKEN'); 
 if(toekn){ 
  //如果請求時toekn存在,就為每次請求的headers中設置好toekn,后台根據headers中的toekn判斷是否放行 
  request.headers.set('toekn',toekn); 
 } 
 next((response) => { 
  return response; 
 }); 
}); 
攔截器 
Vue.http.interceptors.push((request, next) => { 
    //console.log(Login.item); 
    var tokens = localStorage.getItem('token'); 
    request.headers.set('Authorization', tokens); 
    //console.log(request.headers); 
    help.showLoading = true;  
    next((response) => { 
     //console.log(response); 
        help.showLoading = false; 
         return response 
     }) 
}) 

 


免責聲明!

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



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