// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then((response) => {});
取消请求
使用 CancelToken.source :
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
使用 CancelToken 构造函数:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
XMLHttpRequest
XMLHttpRequest(XHR)对象可以与服务器交互,可以从 URL 获取数据,而无需刷新整个页面。
基本用法
readyState
取消请求
Fetch
Fetch 提供了对
Request
和Response
对象的通用定义,使之可以被应用到更多场景中,例如 Service Worker、Cache API 等。基本用法
fetch 返回一个 Promise ,并 resolve 一个 Response 对象,只有在网络故障或主动中断请求时会 reject 。
fetch 与 jQuery.ajax() 的不同
ok
属性会为 false),只有在网络故障或主动中断请求时会 reject 。Set-Cookie
头部字段会被忽略。credentials
。取消请求
通过
AbortSignal API
来中断 fetch 发起的请求。Axios
axios 是一个开源的 http 库,基于 Promise ,可用于浏览器与 Node.js 端。
基本用法
取消请求
使用
CancelToken.source
:使用
CancelToken
构造函数:jQuery.ajax()
基本用法
返回一个
jqXHR
对象取消请求
参考