How to Use the fetch API for Network Requests in HarmonyOS JS Apps
This guide shows how to configure permissions, enable cleartext traffic, create a JS page, import the fetch module, and use fetch.fetch in the onInit lifecycle to retrieve JSON data from an external API and display it in a HarmonyOS UI.
Configure Network Permissions
Add the Internet permission in config.json under the module section:
{
"reqPermissions": [
{
"reason": "",
"name": "ohos.permission.INTERNET"
}
]
}Enable Cleartext HTTP (if needed)
If the request uses plain HTTP, enable cleartext traffic by adding the deviceConfig section:
{
"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
}
}Create a JS Page
In the pages directory, create a new JS page (e.g., fetch) which generates fetch.hml, fetch.js, and fetch.css.
Import the fetch Module
import fetch from '@system.fetch';Make the Request in onInit
Use fetch.fetch inside the page’s onInit lifecycle method to call an external API and store the result in the page data:
onInit() {
// Initiate network request
fetch.fetch({
url: `https://qqlykm.cn/api/api/tq.php?city=北京`,
responseType: "json",
success: (resp) => {
this.winfo = resp.data;
}
});
}Full JS Page Code
import router from '@system.router';
import fetch from '@system.fetch';
export default {
data: {
winfo: "默认数据"
},
goback() {
router.back();
},
onInit() {
// Initiate network request
fetch.fetch({
url: `https://qqlykm.cn/api/api/tq.php?city=北京`,
responseType: "json",
success: (resp) => {
this.winfo = resp.data;
}
});
}
};Design the HML UI
<div class="container">
<button @click="goback">返回</button>
<text>{{ winfo }}</text>
</div>Result
The page displays a button to go back and shows the weather data returned by the API.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
