Axios 是一个基于 HTTP 的桌面客户端,可以在浏览器和 node 运行
非常重要的一个特性就是 axios 可以在发送请求前做准备工作,和请求结果后做结果处理,包括取消请求
自己学习的话首先需要通过 JSON Server 创建一个本地请求环境
// 安装 json-server
npm install -g json-server
// 启动 server
json-server --watch db.json
安装 axios
npm i axios
yarn add axios
一个最简单的 axios 请求体
axios({
// 请求方式
method: '',
// 请求地址,地址后面可以加id
url: '',
// 如果需要传递报文的话,需要设置请求体
data: {
key: value
}
}).then(res => {
console.log(res.data)
})
axios 本身也封装了不同请求的方法函数,直接调用即可
axios 请求响应结构
config - 就是整个请求体的配置对象,包括类型、地址、请求头等
data - 成功返回数据结果,响应体内容
headers - 响应头信息
request - 原生的 ajax 请求对象,XMLHttpRequest 实例对象
status:响应的状态码
statusText:响应状态字符串
axios 配置对象 ( config )
{
// 请求地址
url: '/keyboard',
// 请求方法
method: 'get',
// 请求地址的域名,设置完后 url 只用填写后面的路径即可
baseURL: '<http://localhost:3000>',
// 对请求的数据进行处理,并将处理完的结果发送给服务器
transformRequest: [function (data, headers){
return data
}],
// 对请求的响应结果进行处理,并将处理完的结果返回
transformResponse: [function (data){
return data
}],
// 对请求头信息进行配置
headers: {'X-Requested-With': 'XMLHttpRequest'},
// 添加在地址后的传参
params: {
id: 123
},
// 对请求的参数进行序列化
paramsSerializer: function (params) {},
// 请求体,请求携带的数据,分为json 和 字符串格式,最后都会转成字符串
data: {},
// 请求超时时间,单位毫秒
timeout: 0,
// 跨域请求时对是否携带 cookie 做处理
withCredentials: false,
// 请求的适配器做设置
adapter: function (config) {
/* ... */
},
//
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// 对响应体的格式做设置
responseType: 'json',
// 响应结果的编码
responseEncoding: 'utf8',
// 响应标识
xsrfCookieName: '',
xsrfHeaderName: '',
// 上传 / 下载回调
onUploadProgress / onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
// Do whatever you want with the Axios progress event
},
// 设置响应体的最大尺寸,单位字节
maxContentLength: 2000,
// 设置请求体的最大内容
maxBodyLength: 2000,
// 对响应成功的条件进行设置
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// 最大跳转次数
maxRedirects: 21,
// node中设置,代理转发地址
socketPath: null,
// 对客户端的信息进行设置
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 代理设置
proxy: {
protocol: 'https',
host: '127.0.0.1',
// hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// 对ajax 请求进行取消的设置
cancelToken: new CancelToken(function (cancel) {
}),
// node设置,对响应结果是否解压
decompress: true
}
创建实例对象
const Axios = axios.create({
baseURL: '<https://api.doc>',
timeout: 2000
})
// Axios就是axios的实例,功能基本是一样的,可以直接使用请求函数
Axios.get('/getName').then(res => {
console.log(res.data)
})
拦截器
其实就是一个函数,分为请求拦截器和响应拦截器
执行顺序为 请求拦截器 - 响应拦截器 - 发送请求 , 如果请求拦截器第一步抛出异常则直接进入 响应拦截器的失败函数,我们发送的请求也直接走失败函数
当有多个拦截器时,请求拦截器后进先执行,响应拦截器先进先执行
// 这里的 use 其实内部封装的就是一个 Promise,所以才能同时处理两个函数
// 设置请求拦截器,参数config就是请求对象,可以在拦截器内对其做处理
axios.interceptors.request.use(
function (config) {
// 发送请求前的处理逻辑代码
console.log("1", config)
return config
},
function (error) {
// 发送请求失败的逻辑代码
console.log("2")
return Promise.reject(error)
})
// 设置响应拦截器
axios.interceptors.response.use(
function (response) {
// 执行条件 状态码为 2xx 范围内的
// 处理响应成功的逻辑代码
console.log("3")
return response
},
function (error) {
// 执行条件 状态码非 2xx 范围的
// 处理响应失败的逻辑代码
console.log("4")
return Promise.reject(error)
})
// 发送请求
axios({
method: "POST",
url: "<http://localhost:3000/keyboard>",
})
.then(res => {
console.log("请求成功", res)
})
.catch(err => {
console.log("请求失败", err)
})
取消请求
通过在axios内部设置 cancelToken 取消函数,再绑定到全局变量,通过按钮触发即可
使用场景可以用于根据上一次请求结果来决定是否再次发起请求,减小服务器压力
let stopCancel = null
function handleClick() {
if (stopCancel !== null) stopCancel()
axios({
method: "GET",
url: "<http://localhost:3000/keyboard>",
cancelToken: new axios.CancelToken(function (cancel) {
stopCancel = cancel
}),
})
.then(res => {
console.log("请求成功", res)
stopCancel = null
})
.catch(err => {
console.log("请求失败", err)
})
}
function stopClick() {
stopCancel()
}