马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
@ohos/axios 是一个基于 promise 的网络请求库,它基于 npm 的 Axios 原库进行适配,使其可以在 OpenHarmony 上运行,并相沿其现有用法和特性 。
怎样安装 @ohos/axios
通过以下命令安装 @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));
- });
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |