鸿蒙开发-使用fetch发起网络请求

场景

鸿蒙基于JS搭建HelloWorld并修改国际化文件:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/118274050

在上面基于JS搭建起来Hello World之后,

怎样发起网络请求获取数据。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

fetch API接口

首先需要配置网络访问的权限

在config.json中的module标签中添加

    "reqPermissions": [
      {
        "reason": "",
        "name": "ohos.permission.INTERNET"
      }
    ],

添加位置如下


默认支持https,如果要支持http,需要在config.json里增加network标签,属性标识

"usesCleartext": true。即:

  "deviceConfig": {
    "default": {
      "network": {
        "cleartextTraffic": true
      }
    }
  },

然后在pages下新建一个页面,右键new-JS Page

这里叫fetch,然后就会在pages下面新增fetch页面,下面有hml、js、css。

然后打开js文件

首先需要导入接口模块

import fetch from '@system.fetch';

然后再生命周期函数onInit中通过fetch.fetch发起请求。

    onInit() {
        //发起网络请求
        fetch.fetch({
            url:`https://qqlykm.cn/api/api/tq.php?city=北京`,
            responseType:"json",
            success:(resp)=>
            {
                this.winfo = resp.data;
            }
        });
    }

其中url就是网络请求的url

这里是从网络上找的免费api

然后将接口的返回值给属性winfo

    data: {
        winfo:"默认数据"
    },

完整的js代码为

import router from '@system.router';
import fetch from '@system.fetch';
export default {
    data: {
        winfo:"默认数据"
    },
    goback(){
        router.back();
    },
    onInit() {
        //发起网络请求
        fetch.fetch({
            url:`https://qqlykm.cn/api/api/tq.php?city=北京`,
            responseType:"json",
            success:(resp)=>
            {
                this.winfo = resp.data;
            }
        });
    }
}

其中route和goback是用来实现路由跳转

hml页面上

<div class="container">
    <button @click="goback">返回</button>
    <text >
        {{ winfo }}
    </text>
</div>

效果

fetch的参数有

参数名

类型

必填

说明

url

string

资源地址。

data

string | Object

请求的参数,可选类型是字符串或者json对象。

header

Object

设置请求的header。

method

string

请求方法默认为GET,可选值为:OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE。

responseType

string

默认会根据服务器返回header中的Content-Type确定返回类型,支持文本和json格式。详见success返回值

success

Function

接口调用成功的回调函数。

fail

Function

接口调用失败的回调函数。

complete

Function

接口调用结束的回调函数。

表2 data与Content-Type关系

data

Content-Type

说明

string

不设置

Content-Type默认为 text/plain,data值作为请求的body。

string

任意 Type

data值作为请求的body。

Object

不设置

Content-Type默认为application/x-www-form-urlencoded,data按照资源地址规则进行encode拼接作为请求的body。

Object

application/x-www-form-urlencoded

data按照资源地址规则进行encode拼接作为请求的body。

success返回值:

参数名

类型

说明

code

number

表示服务器的状态code。

data

string | Object

返回数据类型由responseType确定,详见responseType与success中data关系

headers

Object

表示服务器response的所有header。

表3 responseType与success中data关系

responseType

data

说明

string

服务器返回的header中的type如果是text/*或application/json、application/javascript、application/xml,值为文本内容。

text

string

返回文本内容。

json

Object

返回json格式的对象。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用axios或node-fetch时,你可以封装一个常用的请求函数来简化代码和提高可重用性。以下是一个使用axios或node-fetch封装请求的示例: 使用axios封装请求的示例: ```javascript const axios = require('axios'); async function sendRequest(url, method, data) { try { const response = await axios({ method: method, url: url, data: data }); return response.data; } catch (error) { throw new Error(error.message); } } // 使用示例 sendRequest('https://api.example.com/users', 'GET') .then(data => { console.log(data); }) .catch(error => { console.error(error); }); ``` 使用node-fetch封装请求的示例: ```javascript const fetch = require('node-fetch'); async function sendRequest(url, method, data) { try { const response = await fetch(url, { method: method, body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }); const responseData = await response.json(); return responseData; } catch (error) { throw new Error(error.message); } } // 使用示例 sendRequest('https://api.example.com/users', 'GET') .then(data => { console.log(data); }) .catch(error => { console.error(error); }); ``` 在上述示例中,我们封装了一个名为`sendRequest`的函数,该函数接受三个参数:URL、请求方法(GET、POST等)和请求数据(可选)。函数内部使用了axios或node-fetch来发送请求,并处理返回的响应数据。如果请求出现错误,将抛出一个包含错误消息的异常。 你可以根据自己的需求进一步扩展和定制这个封装函数,例如添加请求头、处理其他类型的响应数据等。 希望这个示例对你有帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值