@ohos/axios
是一个基于 promise 的网络请求库,它基于 npm 的 Axios 原库进行适配,使其可以在 OpenHarmony 上运行,并沿用其现有用法和特性 。
如何安装 @ohos/axios
通过以下命令安装 @ohos/axios
:
ohpm install @ohos/axios
安装完成后,可以在 oh-package.json5
文件中查看包是否安装成功 。
接口和属性列表
接口列表
接口 | 参数 | 功能 |
axios(config) | [config]:请求配置 | 发送请求 |
axios.create(config) | [config]:请求配置 | 创建实例 |
axios.request(config) | [config]:请求配置 | 发送请求 |
axios.get(url[, config]) | url:请求地址 [config]:请求配置 | 发送get请求 |
axios.delete(url[, config]) | url:请求地址 [config]:请求配置 | 发送delete请求 |
axios.post(url[, data[, config]]) | url:请求地址 data:发送请求体数据 [config]:请求配置 | 发送post请求 |
axios.put(url[, data[, config]]) | url:请求地址 data:发送请求体数据 [config]:请求配置 | 发送put请求 |
属性列表
属性 | 描述 |
---|---|
axios.defaults[‘xxx’] | 默认设置 。值为请求配置 [config] 中的配置项 例如 axios.defaults.headers 获取头部信息 |
axios.interceptors | 拦截器。参考 [拦截器] 的使用 |
如何使用 @ohos/axios
@ohos/axios
支持泛型参数,由于 ArkTS 不再支持 any
类型,需要指定参数的具体类型。例如,axios.get<T = any, R = AxiosResponse<T>, D = any>(url)
:
T
是响应数据类型。R
是响应体的类型,通常是一个 JSON 对象。D
是请求参数的类型,当发送 GET 请求时,可能会在 URL 中添加一些查询参数 。
发起一个 GET 请求
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(() => {
// 总是会执行
});
发起一个 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));
});
发起多个并发请求
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;
});
错误处理
axios.get<string, AxiosResponse<string>, null>('/user/12345')
.catch((error: AxiosError) => {
console.log(JSON.stringify(error.message));
console.log(JSON.stringify(error.code));
console.log(JSON.stringify(error.config));
});