axios-miniprogram/docs/pages/basics/request.md

92 lines
2.0 KiB
Markdown
Raw Permalink Normal View History

2023-04-14 23:15:49 +08:00
---
title: 发送请求
---
# {{ $frontmatter.title }}
::: tip {{ $frontmatter.title }}
发送任意请求方法的 HTTP 请求。
:::
## 基础用法
2023-04-15 16:21:54 +08:00
可以直接传递 `url` 发送请求,默认发送的是 `GET` 方法请求。
2023-04-14 23:15:49 +08:00
```ts
import axios from 'axios-miniprogram';
axios
.request('https://api.com/test')
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
2023-04-15 16:21:54 +08:00
## 携带请求配置
2023-04-14 23:15:49 +08:00
2023-04-19 12:00:06 +08:00
可以额外传递第二个参数 `config`,用于指定请求方法以及其他配置项。
2023-04-14 23:15:49 +08:00
```ts
import axios from 'axios-miniprogram';
axios
.request('https://api.com/test', {
method: 'POST', // 此时会发送 POST 方法请求
data: {
name: 'test',
password: '123456',
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
2023-04-15 16:21:54 +08:00
## 仅有请求配置
2023-04-14 23:15:49 +08:00
2023-04-19 12:00:06 +08:00
可以直接传递 `config` 发送请求。
2023-04-14 23:15:49 +08:00
```ts
import axios from 'axios-miniprogram';
axios
.request({
url: 'https://api.com/test/:id',
params: {
id: 1,
},
})
.then((response) => {
// 成功之后做些什么
})
.catch((error) => {
// 失败之后做些什么
});
```
2023-04-15 12:20:09 +08:00
2023-04-19 21:36:06 +08:00
## 请求方法
提供一系列基于 `axios.request()` 的请求方法,可以使用请求方法简化请求。
- [axios.options(url, config?)](/method/OPTIONS)
- [axios.get(url, params?, config?)](/method/GET)
- [axios.head(url, params?, config?)](/method/HEAD)
- [axios.post(url, data?, config?)](/method/POST)
- [axios.put(url, data?, config?)](/method/PUT)
- [axios.patch(url, data?, config?)](/method/PATCH)
- [axios.delete(url, params?, config?)](/method/DELETE)
- [axios.trace(url, config?)](/method/TRACE)
- [axios.connect(url, config?)](/method/CONNECT)
2023-04-15 12:20:09 +08:00
## 说明
2023-04-15 16:21:54 +08:00
您可能发现 `axios.request()``axios()` 使用方式完全一致,为什么用法是一样的?
2023-04-15 12:20:09 +08:00
2023-04-15 16:21:54 +08:00
其实它们本就是同一个请求函数,`axios` 是基于 `axios.request` 添加了一系列工具函数改造而来,其目的是为了简化使用。