一、http数据请求
步骤:
1.在module.json5中申请ohos.permission.INTERNET权限
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
...
}
2.在xxx.ets页面中导入:import http from '@ohos.net.http';
3.调用createHttp()方法,创建一个HttpRequest对象
let http2 = http.createHttp();
4.调用该对象的request()方法,传入http请求的url地址和可选参数,发起网络请求
注意:须在aboutToAppear(){}中发送请求,aboutToAppear类同于vue中的create
aboutToAppear() {
//创建
let http2 = http.createHttp();
//发送request请求
http2.request('https://...',
(err,data)=>{
if (!err) {
console.log('data')
//注意!!! JSON.parse转化
let b=JSON.parse(data.result.toString());
this.自定义数据=b.xx;
console.log(this.listArr[0].store_name);//直接打印b,则日志中显示数据类型
}else{
console.log('err:',err);
//销毁
http2.destroy();
}
});
}
二、axios数据请求
步骤:
1.打开https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Faxios
2.下载安装:
ohpm install @ohos/axios
安装:
检查是否安装成功:
3.在module.json5中申请ohos.permission.INTERNET权限
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
...
}
4.在xxx.ets页面导入:import axios from "@ohos/axios";
5.在aboutToAppear(){}中发送请求
aboutToAppear() {
//get请求
axios.get("https://v5.crmeb.net/api/groom/list/3?page=1&limit=9",{
headers:{
'Content-Type':'application/json',
'Authori-Zation':'Bearer xxx'
}
}
).then(({data:{ data }}) => {
console.log(data.list)
this.message = data.list;
console.log(this.message[0].store_name)
}).catch(err => {
console.log("请求失败:", err);
})
}
({data:{ data }}):解析请求到的data数据下的data数据
运行结果: