7.数据请求

Http/Axios 网络请求文档中心

Http

返回字符串

:::warning
免费测试接口地址:

:::

@State result_use: string = ''
async sendHttp() {
//发请求的实例
const req = http.createHttp()
//通过实例发请求
const res = await req.request("https://httpbin.org")
//使用结果
this.result_use = res.result as string
}

Button('发起Http请求')
.onClick(() => {
this.sendHttp()
})
Scroll() {
Text('http请求结果:' + this.result_use)
}.height('40%')

AxiosAxios库

返回:包装了一层的对象,更适合项目

使用时需要安装第三方库,需要指令安装,若在功能目录则全局安装,如果在 entry 模块夏安装则是局部安装

包存放在:oh-package.json5

OpenHarmony三方库中心仓

@State axiosResult_use: string = ''
async sendAxios() {
try {
const res =
await axios.get<object, AxiosResponse<object, null>>("https://apis.juhe.cn")
this.axiosResult_use = JSON.stringify(res.data)
} catch (error) {
console.error(JSON.stringify(error));
}
}

Scroll() {
Text('axios请求结果:' + this.axiosResult_use)
}.height(300)
Button('发起Axios请求')
.onClick(() => {
this.sendAxios()
promptAction.showToast({ message: this.axiosResult_use })
})

rcp文档中心