请求超时设置经过拦截器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