> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Axios 请求封装

## 一、axios 安装

- 使用**npm**安装**axios**

```bash title="安装"
npm install axios
```

- 使用**cnpm**安装**axios**

```bash title="安装"
cnpm install axios
```

- 使用**yarn**安装**axios**

```bash title="安装"
yarn install axios
```

- 使用**cdn**链接**axios**

```html title="代码示例"
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```

## 二、请求数据方法

- **get 请求**：方式一：

```javascript title="请求方式"
axios({
		// 默认请求方式为get
		method: 'get',
		url: 'api',
		// 传递参数
		params: {
			key: value
		},
		// 设置请求头信息
		headers: {
			key: value
		}
		responseType: 'json'
	}).then(response => {
		// 请求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 请求失败，
		console.log(error);
	});
```

- **get 请求**：方式二

```javascript title="请求方式"
axios
    .get("api", {
        // 传递参数
        params: {
            key: value,
        },
        // 设置请求头信息，可以传递空值
        headers: {
            key: value,
        },
    })
    .then((response) => {
        // 请求成功
        let res = response.data;
        console.log(res);
    })
    .catch((error) => {
        // 请求失败，
        console.log(error);
    });
```

- **post 请求**：方式一

```javascript title="请求方式"
// 注：post请求方法有的要求参数格式为formdata格式，此时需要借助 Qs.stringify()方法将对象转换为字符串
	let obj = qs.stringify({
		key: value
	});

	axios({
		method: 'post',
		url: 'api',
		// 传递参数
		data: obj,
		// 设置请求头信息
		headers: {
			key: value
		}
		responseType: 'json'
	}).then(response => {
		// 请求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 请求失败，
		console.log(error);
	});
```

- **post 请求**：方式二

```javascript title="二、请求数据方法"
let data = {
			key: value
		},
		headers = {
			USERID: "",
			TOKEN: ""
		};
	// 若无headers信息时，可传空对象占用参数位置
	axios.post("api", qs.stringify(data), {
		headers
	}
	}).then(response => {
		// 请求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 请求失败，
		console.log(error);
	});
```

## 三、Qs 插件

:::info Qs 使用

- 引用**cdn**或者使用**npm**、**cnpm**或者 **yarn** 进行插件安装
- 使用 **cdn** 时，默认全局变量为 **Qs**
- Qs 基本方法使用
  - **qs.stringify()** 方法：将目标数据转换为 **string** 字符串
  - **qs.parse()** 方法：将对象字符串格式的数据转换为对象格式

:::
