vue-resource请求超时timeout设置
vue-resource请求超时timeout设置
请求超时设置通过拦截器Vue.http.interceptors实现具体代码如下
main.js里在全局拦截器中添加请求超时的方法
方法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请求的地方如下设置即可。
this.$http.get('url',{
params:{.......},
......
_timeout:3000,
onTimeout: (request) => {
alert("请求超时");
}
}).then((response)=>{
});
方法2:超时之后可以在then的第二个error方法中获取,私以为这个方法更好一些
main.js中设置如下
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;
})
})
页面请求设置
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-1020000005802004
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架