从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报 原创 精华

Chris.
发布于 2021-2-4 15:13
浏览
6收藏

在微信小程序中,若需要向远程服务器请求数据,使用wx.request接口即可。从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报-鸿蒙开发者社区

那么在鸿蒙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": {
        "cleartextTraffic": 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';

这里也是有提示的。

从微信小程序到鸿蒙js开发【03】——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类型,随后问题解决。

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

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

    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;
            }
        });

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

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

        <!-- 天气 -->
        <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;
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2021-2-6 16:56:50修改
10
收藏 6
回复
举报
15条回复
按时间正序
/
按时间倒序
angel
angel

在鸿蒙调用天气信息,学到了

回复
2021-2-5 09:34:29
Chris.
Chris.

聚合数据天气预报接口:https://www.juhe.cn/docs/api/id/73

回复
2021-2-5 10:21:44
六合李欣
六合李欣

非常好,期待更多

回复
2021-2-5 17:23:42
鸿蒙张荣超
鸿蒙张荣超

👍👍👍

回复
2021-2-10 21:10:30
狼哥Army
狼哥Army

在HiLog框里,是可以看到console.info()打印的信息的.

1
回复
2021-2-27 00:19:54
Chris.
Chris. 回复了 狼哥Army
在HiLog框里,是可以看到console.info()打印的信息的.

是的,这个后来找到了~感谢指正

1
回复
2021-2-27 09:56:44
wx5cf3e700badef
wx5cf3e700badef

请问一下这是为什么 ,我也是根据你的配置来的,就说没有网络

回复
2021-3-3 18:37:26
Chris.
Chris. 回复了 wx5cf3e700badef
请问一下这是为什么 ,我也是根据你的配置来的,就说没有网络

检查一下你需要请求的域名是否加到domains中

回复
2021-3-4 15:50:11
执剑天涯奈我何
执剑天涯奈我何

需要动态请求怎么进行地址拼接呢,我静态请求可以成功,拼接的请求就一直报错

回复
2021-3-9 14:33:07
wx60c071692b977
wx60c071692b977 回复了 Chris.
检查一下你需要请求的域名是否加到domains中

问题解决了吗?我本地也报:[pc Preview]: no internet

回复
2021-6-9 17:26:13
阿木木lin2
阿木木lin2 回复了 wx60c071692b977
问题解决了吗?我本地也报:[pc Preview]: no internet

用模拟器调试,别用预览器

回复
2021-6-10 16:18:43
Onion?
Onion? 回复了 Chris.
检查一下你需要请求的域名是否加到domains中

域名加了,还是报的这个错

回复
2021-7-25 17:44:19
wx610110194c114
wx610110194c114 回复了 Chris.
是的,这个后来找到了~感谢指正

顺便建议可以直接查找含有”app log“的日志,不过这个日志也有bug有的时候打印不出来,就很怪异

回复
2021-7-28 16:29:54
mb60bede07d2484
mb60bede07d2484 回复了 Chris.
聚合数据天气预报接口:https://www.juhe.cn/docs/api/id/73

好的收到

回复
2021-7-28 16:48:21
A小亮
A小亮

完整的项目能给一下吗

回复
2022-1-9 20:55:59
回复
    相关推荐