You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zepp OS Amazfit手表应用REST API调用Fetch API使用示例咨询

Zepp OS 侧使用Fetch请求REST接口可运行示例

前置要求

  • 所有网络请求逻辑必须写在Side Service(侧边服务)模块内,手表端UI页面不具备直接发起网络请求的能力
  • 需在项目的app.json配置文件中声明网络权限,否则请求会被系统直接拦截
  • 设备侧网络请求自动走Zepp系统代理,不需要额外做网络适配

完整代码实现

1. 侧边服务代码(side_service/index.js)

这部分负责实际发起网络请求,再通过消息通道把结果回传给UI页面

import { fetch } from '@zos/fetch'
import * as messaging from '@zos/messaging'

// 封装通用请求方法
async function fetchRestData(url, reqOptions = {}) {
  const baseConfig = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
    timeout: 10000
  }
  const finalConfig = Object.assign(baseConfig, reqOptions)

  try {
    const res = await fetch(url, finalConfig)
    if (res.status >= 200 && res.status < 300) {
      // 接口返回json格式用res.json(),返回纯文本用res.text()
      const responseData = await res.json()
      return { success: true, data: responseData }
    }
    return { success: false, errMsg: `请求异常,状态码:${res.status}` }
  } catch (e) {
    return { success: false, errMsg: `网络错误:${e.message}` }
  }
}

// 监听UI页发来的请求指令
messaging.onMessage((msg) => {
  if (msg.type === 'FETCH_REQUEST') {
    const { reqId, url, options } = msg.payload
    fetchRestData(url, options).then(result => {
      // 把请求结果回传
      messaging.send({
        type: 'FETCH_RESPONSE',
        payload: { reqId, ...result }
      })
    })
  }
})

2. UI页面代码(page/index.js)

这部分负责向侧边服务发请求指令,接收返回数据后更新页面

import * as messaging from '@zos/messaging'

// 生成请求唯一ID,用于匹配多请求场景下的响应对应关系
function createReqId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
}

Page({
  onInit() {
    // 监听侧边服务回传的请求结果
    messaging.onMessage((res) => {
      if (res.type === 'FETCH_RESPONSE') {
        const { reqId, success, data, errMsg } = res.payload
        if (success) {
          console.log('接口返回数据:', data)
          // 此处编写拿到数据后的页面渲染逻辑
        } else {
          console.log('请求失败:', errMsg)
        }
      }
    })

    // GET请求示例
    const getReqId = createReqId()
    messaging.send({
      type: 'FETCH_REQUEST',
      payload: {
        reqId: getReqId,
        url: '替换为你的实际HTTPS接口地址',
        options: { method: 'GET' }
      }
    })

    // POST请求示例
    const postReqId = createReqId()
    messaging.send({
      type: 'FETCH_REQUEST',
      payload: {
        reqId: postReqId,
        url: '替换为你的实际HTTPS接口地址',
        options: {
          method: 'POST',
          body: JSON.stringify({ key: 'value' })
        }
      }
    })
  }
})

踩坑提示

  • 所有请求地址必须使用HTTPS协议,HTTP明文请求会被系统拦截
  • 单次请求响应体大小建议控制在100KB以内,过大数据会被系统截断导致解析失败
  • 接口需要鉴权的话,直接在headers字段里添加对应鉴权参数(比如Authorization字段)即可
  • 侧边服务生命周期和APP绑定,不要在服务里写死循环等阻塞逻辑,避免影响系统稳定性

内容的提问来源于stack exchange,提问作者Andriy Kryvtsun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 20:57:28