终止 HTTP 请求是一个重要的功能,特别是在需要优化性能、避免不必要的请求或在某些事件发生时(例如用户点击取消)中断正在进行的请求时。以下是如何使用 axios
和 fetch
实现请求终止的方法:
1. axios
axios
使用了 CancelToken 来支持取消请求。
以下是使用 axios
取消请求的例子:
const axios = require('axios');// 创建一个 CancelToken 的源
const CancelToken = axios.CancelToken;
const source = CancelToken.source();axios.get('https://api.example.com/data', {cancelToken: source.token
}).catch(function(thrown) {if (axios.isCancel(thrown)) {console.log('Request canceled', thrown.message);} else {// 处理其他错误}
});// 在需要时取消请求
source.cancel('Operation canceled by the user.');
2. fetch
对于原生的 fetch
API,你可以使用 AbortController 的 signal
属性来取消请求。
以下是使用 fetch
取消请求的示例:
const controller = new AbortController();
const signal = controller.signal;fetch('https://api.example.com/data', { signal }).then(response => response.json()).then(data => console.log(data)).catch(err => {if (err.name === 'AbortError') {console.log('Fetch aborted');} else {console.error('Fetch error: ', err);}});// 在需要时取消请求
controller.abort();
这里,AbortController
和它的 signal
与 fetch
请求相关联。当调用 controller.abort()
时,与该 signal
关联的 fetch
请求将被中断。
总的来说,不论是使用 axios
还是 fetch
,都提供了取消正在进行的 HTTP 请求的能力。这在某些场景下(例如页面卸载或用户取消操作时)能够避免不必要的后续操作或错误处理。