<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios基本使用</title>
</head>
<body>
<button id="btn1">发送get请求</button>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
//这个是设置请求拦截器的api,传入两个回调,第一个成功回调,第二个失败回调。
axios.interceptors.request.use(
function (config) {
console.log("请求拦截器1调用成功");
return config;
},
function (error) {
console.log("请求拦截器1调用失败");
return Promise.reject(error)
}
)
//在main.js设置全局的请求次数,请求的间隙
axios.interceptors.response.use(function (response) {
console.log("响应拦截器1调用成功");
return response;
}, function axiosRetryInterceptor(err) {
var config = err.config;
console.log(config)
// If config does not exist or the retry option is not set, reject
if (!config || !config.retry) return Promise.reject(err);
// Set the variable for keeping track of the retry count
config.__retryCount = config.__retryCount || 0;
// Check if we've maxed out the total number of retries
if (config.__retryCount >= config.retry) {
// Reject with the error
return Promise.reject(err);
}
// Increase the retry count
config.__retryCount += 1;
// Create new promise to handle exponential backoff
var backoff = new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, config.retryDelay || 1);
});
// Return the promise in which recalls axios to retry the request
return backoff.then(function () {
return axios(config);
});
});
//发送get
document.getElementById("btn1").onclick = function () {
axios({
method: "GET",
url: "www.facebook.com",
params: { a: 111111, b: 3333333333 },
data: { a: 11, b: 22 },
// url: "https://jsonplaceholder.typicode.com/todos/1"
}).then(response => {
console.log(response);
})
}
</script>
</html>
Promise.race判断请求是否超时
let controller = new AbortController()
let signal = controller.signal
let timeoutPromise = (timeout) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("我是 timeoutPromise,已经完成了")
controller.abort()
}, timeout)
})
}
let requestPromise = (url) => {
return fetch(url, {
signal
})
}
Promise.race([
timeoutPromise(1000),
requestPromise("https://jsonplaceholder.typicode.com/todos/1")
])
.then(resp => {
console.log(resp)
})
.catch(error => {
console.log(error)
})