請求超時設置經過攔截器Vue.http.interceptors實現具體代碼以下vue
main.js裏在全局攔截器中添加請求超時的方法segmentfault
方法1:超時以後會調用請求中的onTimeoutd方法,then方法不會執行函數
Vue.http.interceptors.push((request, next) => { let timeout; // 若是某個請求設置了_timeout,那麼超過該時間,會終端該(abort)請求,並執行請求設置的鉤子函數onTimeout方法,不會執行then方法。 if (request._timeout) { timeout = setTimeout(() => { if(request.onTimeout) { request.onTimeout(request); request.abort() } }, request._timeout); } next((response) => { clearTimeout(timeout);
return response; }) })
頁面中用到vue-resource請求的地方以下設置便可。vue-resource
this.$http.get('url',{ params:{.......},
...... _timeout:3000, onTimeout: (request) => { alert("請求超時"); } }).then((response)=>{
});
方法2:超時以後能夠在then的第二個error方法中獲取,私覺得這個方法更好一些this
main.js中設置以下url
Vue.http.interceptors.push((request, next) => { let timeout; // 這裡改用 _timeout if (request._timeout) { timeout = setTimeout(() => {
//自定義響應體 status:408,statustext:"請求超時",並返回給下下邊的next next(request.respondWith(request.body, { status: 408, statusText: '請求超時' })); }, request._timeout); } next((response) => {
console.log(response.status)//若是超時輸出408
return response; }) })
頁面請求設置spa
this.$http.get(`repairs/${this.repairs_id}`,{ params:{with:'room;user'}, _timeout:100,//設置超時時間 }).then((response)=>{ },(err)=>{ console.log(err.status);//若是超時,此處輸出408 });
/** * ,%%%%%%%%, * ,%%/\%%%%/\%% * ,%%%\c "" J/%%% * %. %%%%/ o o \%%% * `%%. %%%% _ |%%% * `%% `%%%%(__Y__)%%' * // ;%%%%`\-/%%%' * (( / `%%%%%%%' * \\ .' | * \\ / \ | | * \\/ ) | | * \ /_ | |__ * (___________))))))) 攻城溼 * * _ _ * __ _(_)_ _(_) __ _ _ __ * \ \ / / \ \ / / |/ _` |'_ \ * \ V /| |\ V /| | (_| | | | | * \_/ |_| \_/ |_|\__,_|_| |_| */
參考文章 https://segmentfault.com/q/1010000005800495/a-1020000005802004code