axios
Axios 是一个基于 Promise 的 HTTP 网络请求库,作用于 Node.js 和浏览器中。在服务端使用原生 Node.js http 模块,在客户端使用 XMLHttpRequests。
实例方法
text
// 基础方法
axios(config)
axios.request(config)
// GET 系列方法
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
// POST 系列方法
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
// 表单提交方法(content-type 默认为 multipart/form-data)
axios.postForm(url[, data[, config]])
axios.putForm(url[, data[, config]])
axios.patchForm(url[, data[, config]])使用配置对象调用实例
除了像axios.get()或axios.post()这样使用,我们还可以直接使用实例,如axios(config)。
js
// 配置实例对象
const instance = axios.create({baseUrl: 'http://api.example.com'})
// 使用实例对象
instance.get('/api/test')
instance.post('/api/getUser', {id: 114514})
或
instance({
url: '/api/test',
method: 'get'
})
instance({
url: '/user/getUser',
method: 'post',
data: {
id: 114514
}
})这样使用可以方便拦截请求和响应。
默认配置
你可以指定默认配置,它将作用于每个请求。
text
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';自定义实例默认值
text
// 创建实例时配置默认值
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 创建实例后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;请求配置
text
{
// `url` 是用于请求的服务器 URL
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // 默认值
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
// 你可以修改请求头。
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理
return data;
}],
// 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是与请求一起发送的 URL 参数
// 必须是一个简单对象或 URLSearchParams 对象
params: {
ID: 12345
},
// `paramsSerializer` 是一个可选配置,允许您自定义序列化 `params`。
paramsSerializer: {
//自定义编码器函数,以迭代方式发送键/值对。
encode?: (param: string): string => { /* 在这里进行自定义操作并返回转换后的字符串 */ },
// 整个参数的自定义序列化器函数。允许用户模仿 1.x 之前的行为。
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
//用于格式化参数中数组索引的配置。
indexes: false // 三个可用选项:
// (1) indexes: null (导致没有括号),
// (2) (default) indexes: false (导致空括号),
// (3) indexes: true (引导空字符串).
},
// `data` 是作为请求体被发送的数据
// 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
// 在没有设置 `transformRequest` 时,则必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属: FormData, File, Blob
// - Node 专属: Stream, Buffer
data: {
firstName: 'Fred'
},
// 发送请求体数据的可选语法
// 请求方式 post
// 只有 value 会被发送,key 则不会
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` 指定请求超时的毫秒数。
// 如果请求时间超过 `timeout` 的值,则请求会被中断
timeout: 1000, // 默认值是 `0` (永不超时)
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `adapter` 允许自定义处理请求,这使测试更加容易。
// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
adapter: function (config) {
/* ... */
},
// `auth` HTTP Basic Auth
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示浏览器将要响应的数据类型
// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 浏览器专属:'blob'
responseType: 'json', // 默认值
// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // 默认值
// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
xsrfCookieName: 'XSRF-TOKEN', // 默认值
// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
// `onUploadProgress` 允许为上传处理进度事件
// 浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,
// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,
// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
// 则promise 将会 resolved,否则是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认值
},
// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
// 如果设置为0,则不会进行重定向
maxRedirects: 5, // 默认值
// `socketPath` 定义了在node.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
// 只能指定 `socketPath` 或 `proxy` 。
// 若都指定,这使用 `socketPath` 。
socketPath: null, // default
// `httpAgent` 和 `httpsAgent` 分别定义了在 node.js 中执行 http 和 https 请求时使用的自定义代理。
// 这允许添加诸如 `keepAlive` 之类的选项,这些选项在 Node.js v19.0.0 之前默认未启用。
// 在 Node.js v19.0.0 之后,不再需要自定义代理来启用 `keepAlive`,
// 因为 `http.globalAgent` 已经默认启用了 `keepAlive`。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` 定义了代理服务器的主机名,端口和协议。
// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// see https://axios-http.com/zh/docs/cancellation
cancelToken: new CancelToken(function (cancel) {
}),
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // 默认值
}拦截器
请求拦截器
js
const instance = axios.create({baseUrl: 'http://api.example.com'})
instance.interceptors.request.use((config) => {
// 此处可设置请求头,如:token、Content-Type
config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
config.headers['Content-Type'] = 'application/json'
// 拦截后必须返回 config,否则请求将中断
return config
}, (error) => {
// 发起请求错误,错误原因主要是:请求参数错误、请求超时、请求被中断、网络错误
return Promise.reject(error)
})响应拦截器
js
const instance = axios.create({baseUrl: 'http://api.example.com'})
instance.interceptors.response.use((res) => {
// 拦截响应,对响应数据进行处理
// 数据模型:{ }
return res.data
}, (error) => {
const status = error.response.status
switch (status) {
case 401:
// 401 错误处理
// 重新发起请求(注意做好次数限制)
instance(error.config)
break
default:
console.log('未知错误')
return Promise.reject(error)
break
}
})响应数据模型
上述响应拦截器res的返回数据模型如下:
json
{
"config": {},
"data": {},
"headers": {},
"request": {},
"status": "number",
"statusText": ""
}config请求的配置对象data服务器返回的数据headers服务器返回的响应头request请求的 XMLHttpRequest 实例status服务器返回的 HTTP 状态码statusText响应状态码的 HTTP 状态码
error的模型如下:
json
{
"code": "string",
"message": "",
"name": "string",
"config": {},
"request": {},
"response": {},
"status": "number",
"stack": "string"
}code错误码message错误信息name错误名称config请求的配置对象request请求的 XMLHttpRequestresponse服务器返回的响应数据status响应状态码stack错误堆栈
移除拦截器
创建的拦截器对象有use和eject方法,use方法返回一个id,可以通过eject方法移除拦截器。
js
const interceptor = instance.interceptors.request.use()
instance.interceptors.request.eject(interceptor)取消请求
AbortController
AbortController 是一个接口,它允许您创建一个控制器对象,该对象可以取消一个或多个请求。
AbortController只能取消当前正在执行的请求,无法取消已经完成或尚未发起的请求- 请求必须携带
signal参数才能被取消,这是建立请求与控制器关联的关键标识 abort()调用后,所有使用该 signal 的请求都会被取消- 被取消的请求会返回一个
Promise.reject错误
js
const controller = new AbortController();
async function test() {
const res = await axios.get('/test', {
signal: controller.signal
});
}
// 取消请求
controller.abort()CancelToken
CancelToken 是一个类,它允许您创建一个取消令牌,该令牌可以取消一个或多个请求。
js
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
async function test() {
const res = await axios.get('/test', {
cancelToken: source.token
});
}
// 取消请求(message信息是可选的)
source.cancel('Operation canceled by the user.');