前端实现http请求重试功能

需求情况比较简单: 需要在前端实现一个重试的功能,如果一个请求访问出错(不管是后端服务出错还是网络出错,亦或者是请求的结果不符合预期)均可进行自动重试

直接上代码,代码直接复制到xx.html文件即可运行

<!DOCTYPE html>

<html>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>

//最大重试次数
const MAX_RETRY = 3
//请求超时时间
const REQUEST_TIMEOUT = 15 * 1000
// 重试间隔500ms
const RETRY_INTERVAL = 500 

function sleep(ms){
  return new Promise((resolve)=>setTimeout(resolve,ms));
}


async function request(url,method,params,retry = MAX_RETRY,hookResult = null){

	let res 
	let requireRetry
	try {
		//构造请求的参数
		let config = {
			url: url,
			method: method,
			timeout: REQUEST_TIMEOUT
		}
		if(Object.is(method,'get')){
			config['params'] = params
		}else if (Object.is(method,"post")){
			config['data'] = params
		}
		res = await axios.request(config)
		//发生服务器错误,重试
		if (res && res.status > 500){
			console.log('返回的状态码:', res.status)
			requiretRetry = true
		} 
		//使用调用者逻辑判断,如果未达到期许,重试
		if (hookResult && !hookResult(res)){
			console.log('hookResult函数返回为false,需要重试')
			requiretRetry = true
		}
	}catch(err){
		console.log(err)
		// 发生网络错误,重试
    	requireRetry = true
	}
	if (requireRetry && retry > 0){
    	// 500ms之后重试
    	await sleep(RETRY_INTERVAL)
    	console.log('重试', retry)
    	res = await request(url, method, params, --retry, hookResult)
  	}

	return res
}

//use example

async function test()
{
 	let res =await request("https://www.baidu.com/s","get",{"wd":"hello"})
	console.log("result is : " , res)
}



</script>


<body >  
	
    <button type="button" onclick="test()">Click Me!</button>


</body>



</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章