Axios 使用详解

时间:2025-01-22 08:16:20

Axios 使用详解

使用

axios 的四种使用方式

1. axios(config)

直接将相关配置包括请求 url 作为参数传入到 axios 方法中

axios({
    url: '',
    method: 'get'
}).then(response => {
    ()
}).catch(error => {
    (error)
});
2. axios(url[, config])

还是使用 axios 方法,但是第一个参数传入请求 url,第二个参数传入其他配置参数。

axios('', {
method: 'get'
}).then(response => {
()
}).catch(error => {
(error)
});
3. axios[method](url[, config])

使用 axios 暴露出来的 get,post,delete,put 等请求方法,参数设置同第 2 种 axios(url[, config])

('', {
timeout: 1000
}).then(response => {
()
}).catch(error => {
(error);
});
4. (config)

使用 axios 暴露出来的 request 方法,参数设置同第 1 种 axios(config)

({
url: '',
timeout: 1000
}).then(response => {
()
}).catch(error => {
(error)
});
配置项
url
`url` 是用于请求的服务器 URL,相对路径/绝对路径
url: '/api/users',
method

method 是创建请求时使用的 http 方法,包括 get, post, put, delete 等
method: 'get', // default

baseURL

baseURL 将自动加在 url 前面,除非 url 是一个绝对 URL。
它可以通过设置一个 baseURL 便于为 axios 实例的方法传递相对 URL
baseURL: '/api/'

method

transformRequest 允许在向服务器发送前,修改请求数据
只能用在 ‘PUT’, ‘POST’ 和 ‘PATCH’ 这几个请求方法
后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream

transformRequest: [function (data, headers) {
//对 data 进行任意转换处理
return data;
}],
transformResponse

transformResponse 在传递给 then/catch 前,允许修改响应数据

transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}]
headers

headers 是即将被发送的自定义请求头
headers: {‘X-Requested-With’: ‘XMLHttpRequest’},

params

params 是即将与请求一起发送的 URL 参数
必须是一个无格式对象(plain object)或 URLSearchParams 对象

params: {
name: 'John'
}
paramsSerializer

paramsSerializer 是一个负责 params 序列化的函数

paramsSerializer: function(params) {
return (params, {arrayFormat: 'brackets'})
}
data

data 是作为请求主体被发送的数据
只适用于这些请求方法 ‘PUT’, ‘POST’, 和 ‘PATCH’
在没有设置 transformRequest 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream

data: {
firstName: 'John'
},
timeout

timeout 指定请求超时的毫秒数(0 表示无超时时间)
如果请求花费了超过 timeout 的时间,请求将被中断
timeout: 1000,

adapter

adapter 允许自定义处理请求,以使测试更轻松
返回一个 promise 并应用一个有效的响应

adapter: function (config) {
/_ ... _/
}
auth

auth 表示应该使用 HTTP 基础验证,并提供凭据
这将设置一个 Authorization 头,覆写掉现有的任意使用 headers 设置的自定义 Authorization

auth: {
username: 'janedoe',
password: 's00pers3cret'
}
responseType

responseType 表示服务器响应的数据类型,可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’
responseType: ‘json’, // default

responseEncoding

responseEncoding 表示用于响应数据的解码方式
responseEncoding: ‘utf8’, // default

validateStatus

validateStatus 定义对于给定的 HTTP 响应状态码是 resolve 或 reject promise 。如果 validateStatus 返回 true (或者设置为 nullundefined),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}

cancelToken

cancelToken 指定用于取消请求的 cancel token
cancelToken: new CancelToken(function (cancel) {
})

拦截器

拦截器,类似于中间件的概念,是 axios 的核心功能之一,主要是分为两种:请求拦截器和响应拦截器。有了拦截器,我们能在网络请求之前,对网络请求配置做处理。在返回数据之前,对返回数据做处理。
中间件,拦截器:
一般用于对一个目标方法的前置或后置切片操作,可以将一些额外的脏逻辑写到其他的文件中管理,提高目标方法的简洁性。
使用方式:

//请求拦截器
const requestInterceptor = ((config) => {
//在请求发送前,对请求配置(AxiosRequestConfig)做一些处理
return config;
}, (error) => {
return (error);
});

//移除之前添加的拦截器
(requestInterceptor);

//响应拦截器
((response) => {
//对请求响应数据做一些处理
return response;
}, (error) => {
return (error);
});
取消请求

支持取消请求也是 axios 的一个核心功能,在配置中实现一个 cancelToken 的参数就能取消。

//取消请求
const cancelToken = ;
const source = ();

('/todos/1', {
   cancelToken: 
}).then(response => {
   ();
}).catch(error => {
   if((error)) {
       ();
   } else {
       (error)
   }
});

('canceled by user');
构成

adapters: 主要是网络请求适配器部分的源码,包括浏览器端的 xhr 和 nodejs 端的 http。
cancel: 主要是取消请求的 cancel 和 cancelToken 相关类。
core: axios 的核心功能,重点类有以下几个: Axios, dispatchRequest 和 InterceptorManager。剩余的主要是一些辅助的方法。
├── /core/
│ │ ├── # 定义 Axios 类
│ │ ├── # 用来调用适配器方法发送 http 请求
│ │ ├── # 拦截器构造函数
helper : 帮助类
axios: 定义 axios 库的接口和默认实例
defaults: 默认配置
utils: 工具方法