HarmonyOS NEXT鸿蒙开发:使用axios发HTTP请求 作者:马育民 • 2025-12-11 19:44 • 阅读:10003 # 介绍 Axios ,是一个基于 promise 的网络请求库,可以运行 node.js 和浏览器中。本库基于Axios 原库v1.3.4版本进行适配,使其可以运行在 OpenHarmony,并沿用其现有用法和特性。 - http 请求 - Promise API - request 和 response 拦截器 - 转换 request 和 response 的 data 数据 - 自动转换 JSON data 数据 # 安装 ``` ohpm install @ohos/axios ``` 执行过程如下: [](https://www.malaoshi.top/upload/0/0/1GW2OWCN9AyH.png) # 需要权限 ``` { "name": "ohos.permission.INTERNET" }, ``` 如下图: [](https://www.malaoshi.top/upload/0/0/1GW2OWIyIVKC.png) # 例子 ``` import axios from '@ohos/axios' interface userInfo{ id: number name: string, phone: number } // 向给定ID的用户发起请求 axios.get, null>('/user?ID=12345') .then((response: AxiosResponse)=> { // 处理成功情况 console.info("id" + response.data.id) console.info(JSON.stringify(response)); }) .catch((error: AxiosError)=> { // 处理错误情况 console.info(JSON.stringify(error)); }) .then(()=> { // 总是会执行 }); // 上述请求也可以按以下方式完成(可选) axios.get, null>('/user', { params: { ID: 12345 } }) .then((response:AxiosResponse) => { console.info("id" + response.data.id) console.info(JSON.stringify(response)); }) .catch((error:AxiosError) => { console.info(JSON.stringify(error)); }) .then(() => { // 总是会执行 }); // 支持async/await用法 async function getUser() { try { const response:AxiosResponse = await axios.get, null>(this.getUrl); console.log(JSON.stringify(response)); } catch (error) { console.error(JSON.stringify(error)); } } ``` ### 发送一个 POST 请求 ``` interface user { firstName: string, lastName: string } axios.post, user>('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then((response: AxiosResponse) => { console.info(JSON.stringify(response)); }) .catch((error) => { console.info(JSON.stringify(error)); }); ``` ### 发起多个并发请求 ``` const getUserAccount = ():Promise => { return axios.get, null>('/user/12345'); } const getUserPermissions = ():Promise => { return axios.get, null>('/user/12345/permissions'); } Promise.all([getUserAccount(), getUserPermissions()]) .then((results:AxiosResponse[]) => { const acct = results[0].data as string; const perm = results[1].data as string; ``` 参考: https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Faxios https://developer.huawei.com/consumer/cn/blog/topic/03186424614454080 原文出处:http://www.malaoshi.top/show_1GW2OQaL9i5x.html