溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在vue-resource中使用interceptors攔截器

發(fā)布時間:2021-01-18 14:33:50 來源:億速云 閱讀:207 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)怎么在vue-resource中使用interceptors攔截器,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

前言

攔截器-interceptor

在現(xiàn)代的一些前端框架上,攔截器基本上是很基礎(chǔ)但很重要的一環(huán),比如Angular原生就支持攔截器配置,VUE的Axios模塊也給我們提供了攔截器配置,那么攔截器到底是什么,它有什么用?

攔截器能幫助我們解決的

  • 添加統(tǒng)一的request的參數(shù)

  • 比如header中加入X-Requested-With,比如客戶端需要實現(xiàn)sign和token的驗證機制,比如你可以寫$http.get(‘/files', params),攔截器幫你拼接成 http://www.xxxx.com/1/files 這樣的請求地址

  • 處理統(tǒng)一的responseError

  • 比如重連機制,拿到error.code錯誤碼重連,比如token過期,重新拿到token再次send request

  • 比如統(tǒng)一報錯信息,給所有返回的404來個提示也會很酷

在vue項目使用vue-resource實現(xiàn)異步加載的過程中,需要在任何一個頁面任何一次http請求過程中,增加對token過期的判斷,如果token已過期,需要跳轉(zhuǎn)至登錄頁面。如果要在每個頁面中的http請求操作中添加一次判斷,那將會是一個非常大的修改工作量。那么vue-resource是否存在一個對于任何一次請求響應捕獲的的公共回調(diào)函數(shù)呢?答案是有的!

vue-resource的interceptors攔截器的作用正是解決此需求的妙方。在每次http的請求響應之后,如果設(shè)置了攔截器,會優(yōu)先執(zhí)行攔截器函數(shù),獲取響應體,然后才會決定是否把response返回給then進行接收。那么我們可以在這個攔截器里邊添加對響應狀態(tài)碼的判斷,來決定是跳轉(zhuǎn)到登錄頁面還是留在當前頁面繼續(xù)獲取數(shù)據(jù)。

怎么在vue-resource中使用interceptors攔截器

安裝與引用

NPM: npm install vue-resource --save-dev

/*引入Vue框架*/
import Vue from 'vue'
/*引入資源請求插件*/
import VueResource from 'vue-resource'

/*使用VueResource插件*/
Vue.use(VueResource)

下邊代碼添加在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請求都會先調(diào)用此處方法
    response.body = '...';
    return response;

 });
});

攔截器實例

(1)為請求添加loading效果

通過inteceptor,我們可以為所有的請求處理加一個loading:請求發(fā)送前顯示loading,接收響應后隱藏loading。
具體步驟如下:

//1、添加一個loading組件
<template id='loading-template'>
  <div class='loading-overlay'></div>
</template>

//2、將loading組件作為另外一個Vue實例的子組件
var help = new Vue({
  el: '#help',
  data: {
    showLoading: false
  },
  components: {
    'loading': {
      template: '#loading-template',
    }
  }
})

//3、將該Vue實例掛載到某個HTML元素
<div id='help'>
  <loading v-show='showLoading'></loading>
</div>

//4、添加inteceptor
Vue.http.interceptors.push((request, next) => {
  loading.show = true;
  next((response) => {
    loading.show = false;
    return response;
  });
});

但是,當用戶在畫面上停留時間太久時,視圖數(shù)據(jù)可能已經(jīng)不是最新的了,這時如果用戶刪除或修改某一條數(shù)據(jù),如果這條數(shù)據(jù)已經(jīng)被其他用戶刪除了,服務(wù)器會反饋一個404的錯誤,但由于我們的put和delete請求沒有處理errorCallback,所以用戶是不知道他的操作是成功還是失敗了。這個問題,同樣也可以通過inteceptor解決。

(2)為請求添加共同的錯誤處理方法

//1、繼續(xù)沿用上面的loading組件,在#help元素下加一個對話框
<div id='help'>
  <loading v-show='showLoading' ></loading>
  <modal-dialog :show='showDialog'>
    <header class='dialog-header' slot='header'>
      <h4 class='dialog-title'>Server Error</h4>
    </header>
    <div class='dialog-body' slot='body'>
      <p class='error'>Oops,server has got some errors, error code: {{errorCode}}.</p>
    </div>
  </modal-dialog>
</div>

//2、給help實例的data選項添加兩個屬性
var help = new Vue({
    el: '#help',
    data: {
      showLoading: false,
      showDialog: false,
      errorCode: ''
    },
    components: {
      'loading': {
        template: '#loading-template',
      }
    }
  })

//3、修改inteceptor
Vue.http.interceptors.push((request, next) => {
  help.showLoading = true;
  next((response) => {
    if(!response.ok){
      help.errorCode = response.status;
      help.showDialog = true;
    }
    help.showLoading = false;
    return response;
  });
});

以上就是怎么在vue-resource中使用interceptors攔截器,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI