HarmonyOS技术社区 · 2021年02月05日

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

<span class="colour" style="color: rgb(51, 51, 51);">目录:</span>
1、在config.json配置网络权限和信任域名
2、在js文件中引入fetch模块
3、调用fetch.fetch发送请求
4、处理返回数据需调用JSON.parse()

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">在微信小程序中,若需要向远程服务器请求数据,使用wx.request接口即可。从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">那么在鸿蒙js开发中,请求远程服务器需要如下几步:</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">1、在config.json配置网络权限和信任域名。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">网络权限的配置是在module.reqPermissions中,配置以下三个权限。工具有提示,还是比较友好的。</span></span></span></span>

  "module": {
    "reqPermissions": [
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      },
      {
        "name": "ohos.permission.SET_NETWORK_INFO"
      },
      {
        "name": "ohos.permission.INTERNET"
      }
    ],
......

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">信任域名的配置是在deviceConfig中,默认是一个空对象,需配置成如下形式。</span></span></span></span>

  "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"
              }
            ]
          }
        }
      }
    }
  },

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">在domains数组中,subdomains为是否信任下级域名,name为域名,无需填写协议。如果请求的服务器域名未配置,是无法请求成功的,且工具不会报错。这里一定记得配置服务器域名。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">2、在js文件中引入fetch模块。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">鸿蒙js请求远程服务器的模块为fetch,在js文件的最上方需引入该模块。</span></span></span></span>

import fetch from '@system.fetch';

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">这里也是有提示的。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">3、调用fetch.fetch发送请求。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">来看一下fetch模块的封装,请求的参数,响应的类型,回调函数都可在对象中定义,和wx.request()基本一致。</span></span></span></span>

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

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">比如我在页面初始化执行的方法onInit()中请求聚合数据的天气预报接口,就可以这样写:</span></span></span></span>

`  onInit() {
        // 加载天气预报
        fetch.fetch({
            url: '[http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=xxxxxxxxx](http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=xxxxxxxxx)',
            responseType: 'json',
            success: res => {
                ......
            }
        });
    }`

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">4、处理返回数据需调用JSON.parse()。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">鸿蒙js开发目前调试功能尚不方便,虽有console.log(), console.info()等方法用于打印日志,但实际运行时并未找到日志的打印。所以我只能在视图中划出一小块区域用于调试。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">这里看到虽然responseType已设置为json,但用' . '取其中属性时仍会红线报错,且页面中可以看出并未取到值,可以猜测此时的res.data仍为string类型,需调用JSON.parse()将其转为json类型,随后问题解决。</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报</span></span></span></span>

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

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报</span></span></span></span>

<span class="highlight" style="background-color:rgb(255, 255, 255)"><span class="colour" style="color:rgb(51, 51, 51)"><span class="font" style="font-family:&quot;Microsoft Yahei&quot;, &quot;Helvetica Neue&quot;, Helvetica, &quot;Hiragino Sans GB&quot;, Arial, sans-serif"><span class="size" style="font-size:16px">附上天气预报这一部分的代码:</span></span></span></span>

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

<span class="colour" style="color: rgb(51, 51, 51);">作者:Chris.</span>

想了解更多内容,请访问: 51CTO和华为官方战略合作共建的鸿蒙技术社区https://harmonyos.51cto.com

21_9.jpg

推荐阅读
关注数
2970
内容数
446
华为鸿蒙相关技术,活动及资讯,欢迎关注及加入创作
目录
极术微信服务号
关注极术微信号
实时接收点赞提醒和评论通知
安谋科技学堂公众号
关注安谋科技学堂
实时获取安谋科技及 Arm 教学资源
安谋科技招聘公众号
关注安谋科技招聘
实时获取安谋科技中国职位信息