axios官方文件源
官方指南:https://github.com/tc39/proposal-cancelable-promises(但是:This proposal has been withdrawn)
代码实现
1 | ; |
XMLHttpRequest
同步请求:原理是 XMLHttpRequest 这个可以传第三个参数,但是不建议用同步请求,会把 JS 执行线程卡住
Fetch
AbortController
AbortController接口表示一个控制器对象,允许你根据需要中止一个或多个 Web请求。
文档指南:
https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController
redaxios(Axios has a great API that developers love. Redaxios provides that API in 800 bytes, using native fetch().)
1 | // redaxios(https://github.com/developit/redaxios)中,用AbortController实现的CancelToken |
同步异步
request拦截器执行的时机,默认放异步队列,加了参数的话,则requestinterceptor同步处理;
- https://github.com/axios/axios/blob/master/lib/core/Axios.js
- https://github.com/axios/axios/pull/2702/files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay in the execution of your axios request when the main thread is blocked (a promise is created under the hood for the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
axios.interceptors.request.use(function (config) {
config.headers.test = 'I am only a header!';
return config;
}, null, { synchronous: true });
If you want to execute a particular interceptor based on a runtime check, you can add a runWhen function to the options object. The interceptor will not be executed if and only if the return of runWhen is false. The function will be called with the config object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an asynchronous request interceptor that only needs to run at certain times.
function onGetCall(config) {
return config.method === 'get';
}
axios.interceptors.request.use(function (config) {
config.headers.test = 'special get headers';
return config;
}, null, { runWhen: onGetCall });
core
- cancelToken - config
- if cancelToken
- 在 promise 链式调用的 dispatchRequest 抛出错误,在 adapter 中 request.abort() 取消请求,使 promise 走向 rejected,被用户捕获取消信息
OPML
https://en.wikipedia.org/wiki/OPML
source code
XMLHttpRequest 对象
//这篇文章非常好
- https://medium.com/datadriveninvestor/aborting-cancelling-requests-with-fetch-or-axios-db2e93825a36
- https://mp.weixin.qq.com/s/2ADjfJPge391xpdikM08qQ - 由一个bug引发对axios的刨根问底
withCredentials
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.