Skip to content

axios

一、axios 是什么

  1. 前端最流行的 ajax 请求库
  2. react/vue 官方都推荐使用 axios 发 ajax 请求
  3. github 地址
  4. 中文文档

二、axios 特点

  1. 基本 promise 的异步 ajax 请求库
  2. 浏览器端/node 端都可以使用
  3. 支持请求/响应拦截器
  4. 支持请求取消
  5. 请求/响应数据转换
  6. 批量发送多个请求

三、axios 常用语法

  • axios(config): 通用/最本质的发任意类型请求的方式
  • axios(url[, config]): 可以只指定 url 发 get 请求
  • axios.request(config): 等同于 axios(config)
  • axios.get(url[, config]): 发 get 请求
  • axios.delete(url[, config]): 发 delete 请求
  • axios.post(url[, data, config]): 发 post 请求
  • axios.put(url[, data, config]): 发 put 请求
  • axios.defaults.xxx: 请求的默认全局配置
  • axios.interceptors.request.use(): 添加请求拦截器
  • axios.interceptors.response.use(): 添加响应拦截器
  • axios.create([config]): 创建一个新的 axios(它没有下面的功能)
  • axios.Cancel(): 用于创建取消请求的错误对象
  • axios.CancelToken(): 用于创建取消请求的 token 对象
  • axios.isCancel(): 是否是一个取消请求的错误
  • axios.all(promises): 用于批量执行多个异步请求
  • axios.spread(): 用来指定接收所有成功数据的回调函数的方法

四、难点语法的理解和使用

axios.create(config)

  • 根据指定配置创建一个新的 axios, 也就是每个新 axios 都有自己的配置
  • 返回新的 axios 是一个函数
  • 新 axios 只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的
  • 此语法主要解决:项目中有部分接口的配置需要和另外一部分接口的配置不一样的需求场景

拦截器函数|ajax 请求|请求的回调函数的调用顺序

  • 说明: 调用 axios()并不是立即发送 ajax 请求, 而是需要经历一个较长的流程
  • 流程: 请求拦截器 2 => 请求拦截器 1 => 发 ajax 请求 => 响应拦截器 1 => 响 应拦截器 2 => 请求的回调
  • 注意: 此流程是通过 promise 串连起来的, 请求拦截器传递的是 config, 响应 拦截器传递的是 response

取消请求

  1. 配置 cancelToken 对象
  2. 缓存用于取消请求的 cancel 函数
  3. 在后面特定时机调用 cancel 函数取消请求
  4. 在错误回调中判断如果 error 是 cancel, 做相应处理

五、使用示例代码

html
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>处理链流程</title>

		<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
	</head>
	<body>
		<button onclick="testProducts1()">获取商品列表1</button>
		<button onclick="testProducts2()">获取商品列表2</button>
		<button onclick="cancelReq()">取消请求</button>

		<script>
			// 添加请求拦截器
			axios.interceptors.request.use((config) => {
				// 在准备发请求前,取消未完成的请求
				if (typeof cancel === "function") {
					cancel("取消请求")
				}
				// 添加一个cancelToken的配置
				config.cancelToken = new axios.CancelToken((c) => {
					// c是用于取消当前请求的函数
					// 保存函数,用于之后可能需要取消当前请求
					cancel = c
				})

				return config
			})

			// 添加响应拦截器
			axios.interceptors.response.use(
				(response) => {
					cancel = null
					return response
				},
				(error) => {
					if (axios.isCancel(error)) {
						// 取消请求的处理
						console.log("请求取消的错误", error.message)
						// 中断promise链接
						return new Promise(() => {})
					} else {
						// 请求出错了
						cancel = null
						// 将错误向下传递
						// throw error
						return Promise.reject(error)
					}
				}
			)

			// 用于保存取消请求的函数
			let cancel
			// 发请求
			function testProducts1() {
				axios({
					// 测试请更换去请求地址
					url: "http://localhost:4000/products1",
				}).then(
					(response) => {
						console.log("请求1成功了:" + response)
					},
					(error) => {
						// 只用处理请求失败的情况
						console.log("请求1失败了:" + error.message)
					}
				)
			}

			function testProducts2() {
				// 在准备发请求前,取消未完成的请求
				if (typeof cancel === "function") {
					cancel("取消请求")
				}

				axios({
					// 测试请更换去请求地址
					url: "http://localhost:4000/products2",
				}).then(
					(response) => {
						console.log("请求2成功了:" + response)
					},
					(error) => {
						console.log("请求2失败了:" + error.message)
					}
				)
			}

			// 取消请求
			function cancelReq() {
				// 执行取消请求的函数
				if (typeof cancel === "function") {
					cancel("强制取消请求")
				} else {
					console.log("没有可取消的请求")
				}
			}
		</script>
	</body>
</html>

Released under the MIT License.