【HarmonyOS 4.0】网络请求 - axios

  1. axios 相当于鸿蒙应用项目的一个第三方库,鸿蒙应用项目使用ohpm管理(包括安装,卸载等)第三方库。除了axios,还有很多其他的第三方库可供开发者使用,所有的第三方库都收录在OpenHarmony三方库中心仓

1. 安装 axios 库

1.1 查看 ohpm 安装目录
1.2 把 ohpm 安装目录添加到电脑Path环境变量中
1.3 安装 axios:ohpm i @ohos/axios

2. axios 快速入门

1.1 导入 axios:import axios from @ohos/axios
1.2 创建 axios 实例

const instance = axios.creat({
	baseUrl: 'http://<ip>:<port>',
	timeout: 1000
})

1.3 发送 http 请求

// 获取手机验证码
Button('发送验证码')
	.onClick(() => {
		instance.get('/word/user/code', {params: {phone: this.phone}})
		 .then((response) => {
		 	this.code = response.data.data
		 })
		 .catch((error) => {
			console.info(error)
		 })
	}) 
// 登录
Button('登录')
	.onClick(() => {
	  instance.post('/word/user/login', {params: {phone: this.phone, code: this.code}})
		 .then((response) => {
		 	// response.data.data
		 })
		 .catch((error) => {
			console.info(error)
		 })
	})

1.4 获取请求结果,处理异步操作 async await 1

// 登录
Button('登录')
	.onClick(async () => {
	  let response = await instance.post('/word/user/login', {params: {phone: this.phone, code: this.code}})
	  console.info(response.data.data)
	})

// 登录
Button('登录')
	.onClick(async () => {
		try {
		  let response = await instance.post('/word/user/login', {params: {phone: this.phone, code: this.code}})
		  console.info(response.data.data)
		} catch (error){
		  console.info(error)
		}
	})

3. axios 拦截器

  1. axios 可以分别为请求和响应配置拦截器,请求拦截器可在请求发送前拦截,响应拦截器可以在 then() 和 catch() 方法执行前进行拦截。
    在这里插入图片描述
  2. 在拦截器中,开发者可以对请求的参数或者响应的结果做一些统一的处理,比如在请求拦截器中统一为所有请求增加 token 这一 Header,在响应拦截器中统一处理错误响应。

3.1 请求拦截器

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
	return config
}, (error: AxiosError) => { // 比如手机客户端没有联网
    return Promise.reject(error)
})

3.2 响应拦截器

instance.interceptors.response.use((response: AxiosResponse) => {
   return response
}, (error: AxiosError) => {
   return Promise.reject(error)
})

  1. await关键字:它会等待后面的异步操作执行完成,并解析异步操作的结果。
    加上 await 关键字之后,代码的返回值不再是一个 Promise对象,而是 Promise 当中所包含的这个异步操作的结果,也就是说,我们现在就可以直接接收这个结果。这个结果和 Promise 的 then() 方法的回调函数是一回事,操作成功的异步结果处理完了。
    使用 try {} catch (error) {},可以在 catch 中捕获异常结果,异步操作的异常处理完了。
    使用 async await 关键字能让异步的代码看起来更像同步的代码,可读性要更好,代码更好理解。 ↩︎

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值