axios之dispatchRequest.js源码

dispatchRequest

dispatchRequest.js 是 Axios 中真正发送请求的核心实现,位于 lib/core/dispatchRequest.js

主要做了以下操作:

  1. 使用 AxiosHeaders 处理请求头。
  2. 使用 transformData 对请求数据进行转换。
  3. 处理 [POST、PUT、PATCH] 请求的 Content-Type。
  4. 调用适配器发送请求。
  5. 处理响应成功数据。
  6. 处理非取消请求错误数据。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict';

import transformData from './transformData.js';
import isCancel from '../cancel/isCancel.js';
import defaults from '../defaults/index.js';
import CanceledError from '../cancel/CanceledError.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import adapters from '../adapters/adapters.js';

/**
* 检查请求是否已取消,若已取消则抛出 `CanceledError`。
*/
function throwIfCancellationRequested(config) {
// 检查旧版取消令牌(CancelToken)
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}

// 检查新版取消令牌(AbortController)
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}

/**
* 使用配置的适配器发送请求到服务器
*/
export default function dispatchRequest(config) {
// 在发送请求前检查是否已被取消,抛出 `CanceledError`
throwIfCancellationRequested(config);
// 将 headers 转换为 AxiosHeaders 实例
config.headers = AxiosHeaders.from(config.headers);

// 对请求数据进行转换
config.data = transformData.call(config, config.transformRequest);

// 对 POST、PUT、PATCH 请求设置 Content-Type
// - 如果已有 Content-Type 则不覆盖
// - 否则设置为 `application/x-www-form-urlencoded`
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}

// 获取请求适配器实例(根据环境自动选择:浏览器用 xhr,Node.js 用 http)
const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);

// 调用适配器发送真实请求
return adapter(config).then(
function onAdapterResolution(response) {
// 响应返回后再次检查取消状态
// 防止在请求过程中取消了,但响应仍然返回的情况
throwIfCancellationRequested(config);

// 将响应临时挂载到 config.response
config.response = response;
try {
// 对响应数据进行转换
response.data = transformData.call(config, config.transformResponse, response);
} finally {
// 删除 config.response,避免污染配置对象
delete config.response;
}

// 将响应 headers 转换为 AxiosHeaders 实例,添加到响应对象
response.headers = AxiosHeaders.from(response.headers);

// 返回转换后的响应
return response;
},
function onAdapterRejection(reason) {
// 检查是否为取消错误
if (!isCancel(reason)) {
throwIfCancellationRequested(config);

// Transform response data
if (reason && reason.response) {
config.response = reason.response;
try {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
} finally {
delete config.response;
}
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}

return Promise.reject(reason);
}
);
}


axios之dispatchRequest.js源码
https://www.my-web.cn/axios/dispatchRequest/
发布于
2026年5月12日
许可协议