解决方案:
1.请求1还没有结果返回时,不允许发起请求2,通过loading或控制触发按钮,事件形式实现;
2.取消慢接口的请求。
正确的打开方式:
通过取消慢接口请求,可解决异步请求时序问题引起的搜索关键词跟结果存在不一致的问题:
1.fetch方式:
使用 fetch 发起一个 post 请求:
fetch('http://localhost:3000/getList', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
id: 1
})
}).then(result => {
console.log('result', result);
});
可以使用AbortController来实现请求取消:
this.controller?.abort(); // 重新发起 http 请求之前,取消上一次请求
const controller = new AbortController(); // 创建 AbortController 实例
const signal = controller.signal;
this.controller = controller;
fetch('http://localhost:3000/getList', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
id: 1
}),
signal, // 信号参数,用来控制 http 请求的执行
}).then(result => {
console.log('result', result);
});
2.axios方式:
发起 post 请求:
axios.post('http://localhost:3000/getList', {
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
data: {
id: 1,
},
})
.then(result => {
console.log('result:', result);
});
axios 发起的请求可以通过 cancelToken 来取消。
this.source?.cancel('The request is canceled!');
this.source = axios.CancelToken.source(); // 初始化 source 对象
axios.post('http://localhost:3000/getList', {
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
data: {
id: 1,
},
}, { // 注意是第三个参数
cancelToken: this.source.token, // 这里声明的 cancelToken 其实相当于是一个标记或者信号
})
.then(result => {
console.log('result:', result);
});
3.XMLHttpRequest方式:
发起请求:
var xhr1 = new XMLHttpRequest();
xhr1.open('get', 'https://developer.mozilla.org', true);
xhr1.send();
xhr1.onreadystatechange= function () {
console.log(xhr.responseText, '-- respone');
}
XMLHttpRequest调用对应的xhrInstance.abort() 会终止当前的请求:
xhr1.abort();
var xhr2 = new XMLHttpRequest();
xhr2.open('get', 'https://developer.mozilla.org', true);
xhr2.send();
xhr2.onreadystatechange= function (){
console.log(xhr.responseText, '-- respone');
}