目錄:
在微信小程序中,若需要向遠程服務器請求數據,使用wx.request接口即可。
那么在鴻蒙js開發中,請求遠程服務器需要如下幾步:
1、在config.json配置網絡權限和信任域名。
網絡權限的配置是在module.reqPermissions中,配置以下三個權限。工具有提示,還是比較友好的。
"module": {
"reqPermissions": [
{
"name": "ohos.permission.GET_NETWORK_INFO"
},
{
"name": "ohos.permission.SET_NETWORK_INFO"
},
{
"name": "ohos.permission.INTERNET"
}
],
......
信任域名的配置是在deviceConfig中,默認是一個空對象,需配置成如下形式。
"deviceConfig": {
"default": {
"network": {
"usesCleartext": true,
"securityConfig": {
"domainSettings": {
"cleartextPermitted": true,
"domains": [
{
"subdomains": true,
"name": "apis.juhe.cn"
},
{
"subdomains": true,
"name": "api.seniverse.com"
},
{
"subdomains": true,
"name": "v.juhe.cn"
},
{
"subdomains": true,
"name": "api.tianapi.com"
}
]
}
}
}
}
},
在domains數組中,subdomains為是否信任下級域名,name為域名,無需填寫協議。如果請求的服務器域名未配置,是無法請求成功的,且工具不會報錯。這里一定記得配置服務器域名。
2、在js文件中引入fetch模塊。
鴻蒙js請求遠程服務器的模塊為fetch,在js文件的最上方需引入該模塊。
import fetch from '@system.fetch';
這里也是有提示的。
3、調用fetch.fetch發送請求。
來看一下fetch模塊的封裝,請求的參數,響應的類型,回調函數都可在對象中定義,和wx.request()基本一致。
export default class Fetch {
/**
* Obtains data through the network.
* @param options
*/
static fetch(options: {
/**
* Resource URL.
*/
url: string;
/**
* Request parameter, which can be of the string type or a JSON object.
*/
data?: string | object;
/**
* Request header, which accommodates all attributes of the request.
*/
header?: Object;
/**
* Request methods available: OPTIONS, GET, HEAD, POST, PUT, DELETE and TRACE. The default value is GET.
*/
method?: string;
/**
* The return type can be text, or JSON. By default, the return type is determined based on Content-Type in the header returned by the server.
*/
responseType?: string;
/**
* Called when the network data is obtained successfully.
*/
success?: (data: IFetch) => void;
/**
* Called when the network data fails to be obtained.
*/
fail?: (data: any, code: number) => void;
/**
* Called when the execution is completed.
*/
complete?: () => void;
}): void;
}
比如我在頁面初始化執行的方法onInit()中請求聚合數據的天氣預報接口,就可以這樣寫:
onInit() {
// 加載天氣預報
fetch.fetch({
url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=xxxxxxxxx',
responseType: 'json',
success: res => {
......
}
});
}
4、處理返回數據需調用JSON.parse()。
鴻蒙js開發目前調試功能尚不方便,雖有console.log(), console.info()等方法用於打印日志,但實際運行時並未找到日志的打印。所以我只能在視圖中划出一小塊區域用於調試。
這里看到雖然responseType已設置為json,但用' . '取其中屬性時仍會紅線報錯,且頁面中可以看出並未取到值,可以猜測此時的res.data仍為string類型,需調用JSON.parse()將其轉為json類型,隨后問題解決。
onInit() {
// 加載天氣預報
fetch.fetch({
url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=e4b4e30c713b6e2a24f4a851258c8457',
responseType: 'json',
success: res => {
console.info(JSON.stringify(res.data)); //並未打印日志
let data = JSON.parse(res.data); //必須要加上
this.nowWeather = data.result.realtime;
let dailyWeather = data.result.future;
for(let i in dailyWeather) {
dailyWeather[i].date = dailyWeather[i].date.substr(5, 5);
}
this.dailyWeather = dailyWeather;
}
});
附上天氣預報這一部分的代碼:
<!-- 天氣 -->
<div class="weather">
<div class="now" if="{{ nowWeather }}">
<text class="nowPhe">
{{ nowWeather.info }}
</text>
<text>
{{ nowWeather.temperature }}˚C
</text>
<div class="nowOther">
<text>
風力風向: {{ nowWeather.direct }} {{ nowWeather.power }}
</text>
<text>
空氣質量: {{ nowWeather.aqi }}
</text>
</div>
</div>
<div class="daily" if="{{ dailyWeather }}">
<block for="{{ dailyWeather }}">
<div class="dailyItem">
<text>
{{ $item.date }}
</text>
<text>
{{ $item.weather }}
</text>
<text>
{{ $item.temperature }}
</text>
</div>
</block>
</div>
</div>
<!-- 天氣end -->
/*天氣*/
.weather {
background-image: url('./common/weatherbg.jpg');
background-size: contain;
}
.weather text {
color: #fdfdfd;
}
.now {
width: 100%;
height: 260px;
margin-top: 30px;
display: flex;
align-items: center;
justify-content: space-around;
}
.now>text {
font-size: 60px;
}
.nowPhe {
margin-left: 20px;
}
.nowOther {
margin-right: 20px;
display: flex;
flex-direction: column;
height: 220px;
justify-content: space-around;
}
.daily{
margin-top: 30px;
display: flex;
flex-direction: column;
}
.dailyItem{
margin: 0 30px 0 30px;
height: 120px;
border-bottom: 1px solid #bbbbbb;
display: flex;
justify-content: space-between;
align-items: center;
}
作者:Chris.
想了解更多內容,請訪問: 51CTO和華為官方戰略合作共建的鴻蒙技術社區https://harmonyos.51cto.com