🎉 博客主页:【剑九_六千里-优快云博客】【剑九_六千里-掘金社区】
🎨 上一篇文章:【HarmonyOS第八章:HTTP数据请求】
🎠 系列专栏:【HarmonyOS系列】
💖 感谢大家点赞👍收藏⭐评论✍
1. 配置环境变量
运行 ohpm --version 或 ohpm -V 查看 ohpm 是否可运行,如显示版本号则跳过配置环境变量的步骤,如果报以下错误,则按当前步骤执行:
报错原因:未配置 ohpm 环境变量:
2. 下载安装 @ohos/axios
打开鸿蒙第三方库,找到 @ohos/axios
:
根据文档安装即可。
ohpm install @ohos/axios
在 oh-package.json5 文件查看包是否安装成功:
3. @ohos/axios 接口和属性列表
3.1. 接口列表
3.2. 属性列表
4. 使用 @ohos/axios
4.1. 发起一个 GET 请求
axios
支持泛型参数,由于ArkTS
不再支持any
类型,需指定参数的具体类型。 如:axios.get<T = any, R = AxiosResponse<T>, D = any>(url)
- T: 是响应数据类型。当发送一个
POST
请求时,客户端可能会收到一个JSON
对象。T 就是这个JSON
对象的类型。默认情况下,T
是any
,这意味着可以接收任何类型的数据。 - R: 是响应体的类型。当服务器返回一个响应时,响应体通常是一个
JSON
对象。R
就是这个JSON
对象的类型。默认情况下,R
是AxiosResponse<T>
,这意味着响应体是一个AxiosResponse
对象,它的data
属性是T
类型的 - D: 是请求参数的类型。当发送一个
GET
请求时,可能会在URL
中添加一些查询参数。D
就是这些查询参数的类型。参数为空情况下,D
是null
类型。
import axios from '@ohos/axios'
interface userInfo{
id: number
name: string,
phone: number
}
// 向给定ID的用户发起请求
axios.get<userInfo, AxiosResponse<userInfo>, null>('/user?ID=12345')
.then((response: AxiosResponse<userInfo>)=> {
// 处理成功情况
console.info("id" + response.data.id)
console.info(JSON.stringify(response));
})
.catch((error: AxiosError)=> {
// 处理错误情况
console.info(JSON.stringify(error));
})
.then(()=> {
// 总是会执行
});
// 上述请求也可以按以下方式完成(可选)
axios.get<userInfo, AxiosResponse<userInfo>, null>('/user', {
params: {
ID: 12345
}
})
.then((response:AxiosResponse<userInfo>) => {
console.info("id" + response.data.id)
console.info(JSON.stringify(response));
})
.catch((error:AxiosError) => {
console.info(JSON.stringify(error));
})
.then(() => {
// 总是会执行
});
// 支持async/await用法
async function getUser() {
try {
const response:AxiosResponse = await axios.get<string, AxiosResponse<string>, null>(this.getUrl);
console.log(JSON.stringify(response));
} catch (error) {
console.error(JSON.stringify(error));
}
}
4.2. 发送一个 POST 请求
interface user {
firstName: string,
lastName: string
}
axios.post<string, AxiosResponse<string>, user>('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then((response: AxiosResponse<string>) => {
console.info(JSON.stringify(response));
})
.catch((error) => {
console.info(JSON.stringify(error));
});
4.3. 发起多个并发请求
const getUserAccount = ():Promise<AxiosResponse> => {
return axios.get<string, AxiosResponse<string>, null>('/user/12345');
}
const getUserPermissions = ():Promise<AxiosResponse> => {
return axios.get<string, AxiosResponse<string>, null>('/user/12345/permissions');
}
Promise.all<AxiosResponse>([getUserAccount(), getUserPermissions()])
.then((results:AxiosResponse[]) => {
const acct = results[0].data as string;
const perm = results[1].data as string;
});
更多配置请查看@ohos/axios官方文档。
4.4. 实际项目使用
- 导出 axios
- 使用 axios 上的方法
- 配置类型规则
import axios, {
AxiosResponse, AxiosError } from "@ohos/axios"