从微信小程序到鸿蒙JS开发【03】-fetch获取数据&简单天气预报

开发
文章由鸿蒙社区产出,想要了解更多内容请前往:51CTO和华为官方战略合作共建的鸿蒙技术社区https://harmonyos.51cto.com/#zz

[[381065]]

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com/#zz

在微信小程序中,若需要向远程服务器请求数据,使用wx.request接口即可。


那么在鸿蒙js开发中,请求远程服务器需要如下几步:

1、在config.json配置网络权限和信任域名。

网络权限的配置是在module.reqPermissions中,配置以下三个权限。工具有提示,还是比较友好的。

  1.   "module": { 
  2.     "reqPermissions": [ 
  3.       { 
  4.         "name""ohos.permission.GET_NETWORK_INFO" 
  5.       }, 
  6.       { 
  7.         "name""ohos.permission.SET_NETWORK_INFO" 
  8.       }, 
  9.       { 
  10.         "name""ohos.permission.INTERNET" 
  11.       } 
  12.     ], 
  13. ...... 

 信任域名的配置是在deviceConfig中,默认是一个空对象,需配置成如下形式。

  1. "deviceConfig": { 
  2.   "default": { 
  3.     "network": { 
  4.       "usesCleartext"true
  5.       "securityConfig": { 
  6.         "domainSettings": { 
  7.           "cleartextPermitted"true
  8.           "domains": [ 
  9.             { 
  10.               "subdomains"true
  11.               "name""apis.juhe.cn" 
  12.             }, 
  13.             { 
  14.               "subdomains"true
  15.               "name""api.seniverse.com" 
  16.             }, 
  17.             { 
  18.               "subdomains"true
  19.               "name""v.juhe.cn" 
  20.             }, 
  21.             { 
  22.               "subdomains"true
  23.               "name""api.tianapi.com" 
  24.             } 
  25.           ] 
  26.         } 
  27.       } 
  28.     } 
  29.   } 
  30. }, 

 在domains数组中,subdomains为是否信任下级域名,name为域名,无需填写协议。如果请求的服务器域名未配置,是无法请求成功的,且工具不会报错。这里一定记得配置服务器域名。

2、在js文件中引入fetch模块。

鸿蒙js请求远程服务器的模块为fetch,在js文件的最上方需引入该模块。

  1. import fetch from '@system.fetch'

这里也是有提示的。


3、调用fetch.fetch发送请求。

来看一下fetch模块的封装,请求的参数,响应的类型,回调函数都可在对象中定义,和wx.request()基本一致。

  1. export default class Fetch { 
  2.   /** 
  3.    * Obtains data through the network. 
  4.    * @param options 
  5.    */ 
  6.   static fetch(options: { 
  7.     /** 
  8.      * Resource URL. 
  9.      */ 
  10.     url: string; 
  11.  
  12.     /** 
  13.      * Request parameter, which can be of the string type or a JSON object. 
  14.      */ 
  15.     data?: string | object; 
  16.  
  17.     /** 
  18.      * Request header, which accommodates all attributes of the request. 
  19.      */ 
  20.     header?: Object; 
  21.  
  22.     /** 
  23.      * Request methods available: OPTIONS, GET, HEAD, POST, PUT, DELETE and TRACE. The default value is GET. 
  24.      */ 
  25.     method?: string; 
  26.  
  27.     /** 
  28.      * 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. 
  29.      */ 
  30.     responseType?: string; 
  31.  
  32.     /** 
  33.      * Called when the network data is obtained successfully. 
  34.      */ 
  35.     success?: (data: IFetch) => void; 
  36.  
  37.     /** 
  38.      * Called when the network data fails to be obtained. 
  39.      */ 
  40.     fail?: (data: any, code: number) => void; 
  41.  
  42.     /** 
  43.      * Called when the execution is completed. 
  44.      */ 
  45.     complete?: () => void; 
  46.   }): void; 

 比如我在页面初始化执行的方法onInit()中请求聚合数据的天气预报接口,就可以这样写:

  1. onInit() { 
  2.       // 加载天气预报 
  3.       fetch.fetch({ 
  4.           url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=xxxxxxxxx'
  5.           responseType: 'json'
  6.           success: res => { 
  7.               ...... 
  8.           } 
  9.       }); 
  10.   } 

 4、处理返回数据需调用JSON.parse()。

鸿蒙js开发目前调试功能尚不方便,虽有console.log(), console.info()等方法用于打印日志,但实际运行时并未找到日志的打印。所以我只能在视图中划出一小块区域用于调试。

这里看到虽然responseType已设置为json,但用' . '取其中属性时仍会红线报错,且页面中可以看出并未取到值,可以猜测此时的res.data仍为string类型,需调用JSON.parse()将其转为json类型,随后问题解决。


  1. onInit() { 
  2.        // 加载天气预报 
  3.        fetch.fetch({ 
  4.            url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=e4b4e30c713b6e2a24f4a851258c8457'
  5.            responseType: 'json'
  6.            success: res => { 
  7.                console.info(JSON.stringify(res.data)); //并未打印日志 
  8.                let data = JSON.parse(res.data); //必须要加上 
  9.                this.nowWeather = data.result.realtime; 
  10.                let dailyWeather = data.result.future; 
  11.                for(let i in dailyWeather) { 
  12.                    dailyWeather[i].date = dailyWeather[i].date.substr(5, 5); 
  13.                } 
  14.                this.dailyWeather = dailyWeather; 
  15.            } 
  16.        }); 

 

附上天气预报这一部分的代码:

  1. <!-- 天气 --> 
  2.     <div class="weather"
  3.         <div class="now" if="{{ nowWeather }}"
  4.             <text class="nowPhe"
  5.                 {{ nowWeather.info }} 
  6.             </text> 
  7.             <text> 
  8.                 {{ nowWeather.temperature }}˚C 
  9.             </text> 
  10.             <div class="nowOther"
  11.                 <text> 
  12.                     风力风向: {{ nowWeather.direct }} {{ nowWeather.power }} 
  13.                 </text> 
  14.                 <text> 
  15.                     空气质量: {{ nowWeather.aqi }} 
  16.                 </text> 
  17.             </div> 
  18.         </div> 
  19.         <div class="daily" if="{{ dailyWeather }}"
  20.             <block for="{{ dailyWeather }}"
  21.                 <div class="dailyItem"
  22.                     <text> 
  23.                         {{ $item.date }} 
  24.                     </text> 
  25.                     <text> 
  26.                         {{ $item.weather }} 
  27.                     </text> 
  28.                     <text> 
  29.                         {{ $item.temperature }} 
  30.                     </text> 
  31.                 </div> 
  32.             </block> 
  33.         </div> 
  34.     </div>         
  35.     <!-- 天气end --> 

  1. /*天气*/ 
  2. .weather { 
  3.     background-image: url('./common/weatherbg.jpg'); 
  4.     background-size: contain; 
  5. .weather text { 
  6.     color: #fdfdfd; 
  7. .now { 
  8.     width: 100%; 
  9.     height: 260px; 
  10.     margin-top: 30px; 
  11.     display: flex; 
  12.     align-items: center; 
  13.     justify-content: space-around; 
  14. .now>text { 
  15.     font-size: 60px; 
  16. .nowPhe { 
  17.     margin-left: 20px; 
  18. .nowOther { 
  19.     margin-right: 20px; 
  20.     display: flex; 
  21.     flex-direction: column
  22.     height: 220px; 
  23.     justify-content: space-around; 
  24. .daily{ 
  25.     margin-top: 30px; 
  26.     display: flex; 
  27.     flex-direction: column
  28. .dailyItem{ 
  29.     margin: 0 30px 0 30px; 
  30.     height: 120px; 
  31.     border-bottom: 1px solid #bbbbbb; 
  32.     display: flex; 
  33.     justify-content: space-between
  34.     align-items: center; 

 想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com/#zz

【编辑推荐】

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2021-02-23 12:25:26

鸿蒙HarmonyOS应用开发

2013-04-10 17:59:50

微信公众平台接口开发

2021-03-02 09:29:29

鸿蒙HarmonyOS应用开发

2021-02-20 09:52:02

鸿蒙HarmonyOS应用开发

2021-02-25 10:01:19

鸿蒙HarmonyOS应用开发

2021-02-22 14:56:55

鸿蒙HarmonyOS应用开发

2021-02-23 12:23:57

鸿蒙HarmonyOS应用开发

2021-02-21 11:09:18

鸿蒙HarmonyOS应用开发

2021-02-05 09:46:16

鸿蒙HarmonyOSjs开发

2021-02-23 09:52:42

鸿蒙HarmonyOS应用开发

2021-02-04 13:49:41

鸿蒙HarmonyOS应用开发

2021-02-25 15:13:08

鸿蒙HarmonyOS应用开发

2016-03-14 10:29:38

天气预报各类工具源码

2017-08-01 10:10:32

人工智能智能天气预报

2021-02-24 09:36:03

鸿蒙CSS应用开发

2009-07-07 09:25:08

Linux开发FOSS开发项目

2013-03-26 13:20:27

Android天气预报

2018-01-29 11:25:37

LinuxASCII 字符天气预报

2020-02-11 20:00:29

开源开源工具天气预报

2010-08-13 10:56:58

FlexWebservice
点赞
收藏

51CTO技术栈公众号