鸿蒙应用开发中如何发送Axios请求?
我们先进行简单的代码测试,如下图:
1、导入Axios包
鸿蒙当中使用axios需要安装,在控制台输入 ohpm install @ohos/axios
安装完成后在oh-package.json5文件中查看是否安装成功:
2、设置拦截器
import { promptAction } from '@kit.ArkUI';
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';
import { BASE_URL } from '../constants';
/**
* 后端响应基本类型«result»
*/
export interface ServiceResponse<T> {
/** 请求码,200为成功,300及300以上为请求失败 */
code: number;
msg: string;
resTime: Date;
result: T;
tips: string;
}
// type 类型别名,保存类型(类似变量声明的关键词 const let)
// 三层对象嵌套:Axios 响应类型 > 后端响应基本类型 > 不同接口响应的类型
export type AxiosResponseData<Result = null> = AxiosResponse<ServiceResponse<Result>, null>
// 创建实例
export const axiosInstance = axios.create({
baseURL: BASE_URL, // 请求基地址
timeout: 1000 * 20 // 请求超时时间
})
// --- 从官方文档中复制过来拦截器的基本结构,把 axios 修改成 axiosInstance ---
// 拦截器分为两部分:请求拦截器、响应拦截器
// 添加请求拦截器
axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// 对请求数据做点什么
return config;
}, (error: AxiosError) => {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axiosInstance.interceptors.response.use((response: AxiosResponseData) => {
// 对响应数据做点什么,then 响应成功时
// response.data.code 是服务器的业务状态码
if (response.data.code !== 200) {
// 把后端响应的错误信息,通过轻提示,提醒用户
promptAction.showToast({ message: response.data.msg })
// 主动返回错误,避免 await 后续代码执行
return Promise.reject(response.data.msg)
}
return response;
}, (error: AxiosError) => {
// 对响应错误做点什么,catch 响应失败时
if (error.message.includes('401')) {
// 401 Unauthorized 身份验证出问题了 token
promptAction.showToast({ message: '登录信息无效,请重新登录' })
} else if (error.message.includes('404')) {
// 404 Not Found 服务器找不到请求的资源
promptAction.showToast({ message: '无法识别的 URL,请检查' })
} else {
promptAction.showToast({ message: '未知网络请求错误' })
}
// 未知错误
return Promise.reject(error);
});
3、测试
import { AxiosResponse } from '@ohos/axios';
import { postUserLoginPasswdAPI } from '../../api';
import { axiosInstance } from '../../common/utils';
/**
* 账号密码登录模型
*/
export interface PostUserLoginPasswdData {
/** 用户密码 */
passwd?: string;
/** 用户手机号 */
phone?: string;
}
/**
* 数据响应模型«result»
*/
export interface ServiceResponse<T> {
/**
* 请求码,200为成功,300及300以上为请求失败
*/
code: number;
/**
* 响应信息
*/
msg: string;
/**
* 响应时间
*/
resTime: Date;
result: T;
tips: string;
}
/**
* 用户登录信息
*/
export interface ServiceResponseResult {
/**
* 访问token,有效期1小时
*/
accessToken?: string;
/**
* 头像
*/
avatar?: string;
/**
* 昵称
*/
nickname?: string;
/**
* 续期token,有效期30天
*/
renewalToken?: string;
}
// type 类型别名,保存类型(类似变量声明的关键词 const let)
type AxiosResponseData<Result> = AxiosResponse<ServiceResponse<Result>, null>
// 创建一个 axios 实例,内部做一些 axios 通用配置,如 baseURL(基础地址,自动拼接)
// export const axiosInstance = axios.create({
// baseURL: BASE_URL // 基础地址
// })
@Entry
@Component
struct AxiosTestPage {
@State avatar: string = ''
build() {
Navigation() {
Scroll() {
Column({ space: 10 }) {
Button('发送请求-约束请求参数格式')
.onClick(async () => {
// axios.post<参数1, 参数2, 参数3> 范型
// 范型参数1: 没啥用,会被第二个参数覆盖
// 范型参数2: 用于指定后端返回数据的类型(重要)
// 范型参数3: 请求参数
const res = await axiosInstance.post<null,
AxiosResponseData<ServiceResponseResult>,
PostUserLoginPasswdData>
(
'/user/login/passwd', // 小括号参数1:接口地址地址
{ phone: '120666666', passwd: '888itcast.CN764%...' } // 小括号参数2:请求参数,可通过范型约束类型
)
AlertDialog.show({ message: JSON.stringify(res, null, 2) })
if (res.data.code === 200) {
this.avatar = res.data.result.avatar || ''
}
})
Button('发送请求2-测试错误')
.onClick(async () => {
const res = await axiosInstance.post<null,
AxiosResponseData<ServiceResponseResult>,
PostUserLoginPasswdData>
(
'/user/login/passwd', // 接口地址地址
{ phone: '1123', passwd: '111' } // 请求参数,可通过范型约束类型
)
this.avatar = res.data.result.avatar || ''
})
Button('发送请求3-测试错误')
.onClick(async () => {
const res = await axiosInstance.post<null,
AxiosResponseData<ServiceResponseResult>,
PostUserLoginPasswdData>
(
'/user/login/111', // 接口地址地址
{ phone: '120666666667', passwd: '888itcast.CN764%...' } // 请求参数,可通过范型约束类型
)
this.avatar = res.data.result.avatar || ''
})
Button('发送请求4-调用素材的接口')
.onClick(async () => {
// 调用素材中封装好的接口
const res = await postUserLoginPasswdAPI({
phone: '120666666667',
passwd: '888itcast.CN764%...'
})
this.avatar = res.data.result.avatar || ''
})
Image(this.avatar)
.width(200)
}
.constraintSize({ minHeight: '100%' })
}
.width('100%')
.height('100%')
}
.title('@ohos/axios 网络请求库')
.titleMode(NavigationTitleMode.Mini)
}
}