【HarmonyOS 4.0】网络请求 - axios

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

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 实例

ts 复制代码
const instance = axios.creat({
	baseURL: 'http://<ip>:<port>',
	timeout: 1000
})

1.3 发送 http 请求

ts 复制代码
// 获取手机验证码
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^

ts 复制代码
// 登录
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 请求拦截器

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

3.2 响应拦截器

ts 复制代码
instance.interceptors.response.use((response: AxiosResponse) => {
   return response
}, (error: AxiosError) => {
   return Promise.reject(error)
})

4. 代码示例

entey/src/main/ets/http/Axios.ets文件写入

ts 复制代码
import axios, { InternalAxiosRequestConfig, AxiosError, AxiosResponse } from '@ohos/axios'
import { promptAction } from '@kit.ArkUI';

export const instance = axios.create({
  baseURL: 'http://xxx.xxx.xxx.xxx:xxxx',
  timeout: 1000,
});

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = AppStorage.get('token')
  if (token) {
    config.headers['token'] = token
  }
  return config
}, (error: AxiosError) => {
  promptAction.showToast({ message: error.message })
  return Promise.reject(error)
});

instance.interceptors.response.use((response: AxiosResponse) => {
  if (response.data.code === 200) {
    return response
  } else {
    promptAction.showToast({ message: response.data.message })
    return Promise.reject(response.data.message)
  }
}, (error: AxiosError) => {
  promptAction.showToast({ message: error.message })
  return Promise.reject(error)
})

entey/src/main/ets/http/Api.ets文件写入

ts 复制代码
import { instance } from './Axios'

export function sendCode(phone: string) {
  return instance.get('/word/user/code', { params: { phone: phone } })
}

interface loginParams {
  phone: string,
  code: string
}

export function login(params: loginParams) {
  return instance.post('/word/user/login', params)
}

  1. await关键字:它会等待后面的异步操作执行完成,并解析异步操作的结果。

    加上 await 关键字之后,代码的返回值不再是一个 Promise对象,而是 Promise 当中所包含的这个异步操作的结果,也就是说,我们现在就可以直接接收这个结果。这个结果和 Promise 的 then() 方法的回调函数是一回事,操作成功的异步结果处理完了。

    使用 try {} catch (error) {},可以在 catch 中捕获异常结果,异步操作的异常处理完了。

    使用 async await 关键字能让异步的代码看起来更像同步的代码,可读性要更好,代码更好理解。 ↩︎

相关推荐
卿卿qing19 天前
【HarmonyOS 4.0】@ohos.router 页面路由
harmonyos 4.0
卿卿qing22 天前
【HarmonyOS 4.0】UI结构复用
harmonyos 4.0