更新记录

1.0.0(2026-12-05)

1.增加服务发布功能


平台兼容性

uni-app(5.38)

Vue2 Vue2插件版本 Vue3 Vue3插件版本 Chrome Safari app-vue app-vue插件版本 app-nvue Android Android插件版本 iOS 鸿蒙
√ 1.0.0 √ 1.0.0 × × √ 1.0.0 - 7.0 1.0.0 × ×
微信小程序 支付宝小程序 抖音小程序 百度小程序 快手小程序 京东小程序 鸿蒙元服务 QQ小程序 飞书小程序 小红书小程序 快应用-华为 快应用-联盟
× × × × × × × × × × × ×

uni-app x(5.38)

Chrome Safari Android Android插件版本 iOS 鸿蒙 微信小程序 支付宝小程序
× × 7.0 1.0.0 × × - -

其他

多语言 暗黑模式 宽屏模式 蒸汽模式
× × × √

Android HTTP 服务端插件

将本目录 hawkeye-http-server 复制到目标 uni-app 项目的 uni_modules/ 下。在 HBuilderX 中运行到 Android 手机,插件会随 App 构建。适用于 Vue 2 和 Vue 3 的 uni-app Android App,最低 Android 6.0(API 23),使用 HBuilderX 5.15 验证。插件自带 Android 网络权限声明,使用系统网络库。

服务启动后监听手机的 IPv4 网络接口。同一台手机可使用 http://127.0.0.1:8080,局域网内的设备使用 started 事件返回的手机地址。下面的示例在同一个端口上注册多个接口。

Vue 3 接入示例

Vue 2 项目可使用 Options API 示例。

将以下内容保存到目标项目的 pages/http-demo/index.vue,并在项目的 pages.json 注册 pages/http-demo/index。

<template>
  <view class="http-demo">
    <view class="demo-shell">
      <view class="demo-service">
        <view class="demo-heading">
          <text class="demo-title">HTTP 服务端</text>
          <text class="demo-port demo-mono">端口 {{ port }}</text>
        </view>
        <view class="demo-console" role="status">
          <text class="demo-caption">服务状态与地址</text>
          <text class="demo-output demo-mono" selectable>{{ status }}</text>
        </view>
        <view class="demo-actions">
          <button class="demo-button demo-start" :disabled="active" @click="start">启动服务</button>
          <button class="demo-button demo-stop" :disabled="!active" @click="stop">停止服务</button>
        </view>
      </view>

      <view class="demo-panel">
        <view class="demo-heading">
          <text class="demo-panel-title">本机 IPv4</text>
          <button class="demo-button demo-lookup" @click="showLocalIps">获取本机 IP</button>
        </view>
        <text class="demo-ip demo-mono" selectable role="status">{{ localIpStatus }}</text>
      </view>

      <view class="demo-panel">
        <text class="demo-panel-title">示例路由</text>
        <view v-for="route in routes" :key="route.id" class="demo-route">
          <text class="demo-method demo-mono" :class="{ 'demo-method-write': route.method === 'POST' }">{{ route.method }}</text>
          <text class="demo-path demo-mono" selectable>{{ route.path }}</text>
          <text class="demo-mode">{{ route.dynamic ? '动态响应' : '固定响应' }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onHide, onUnload } from '@dcloudio/uni-app'
// #ifdef APP-PLUS
import {
  getLocalIpAddresses,
  startHttpServer,
  stopHttpServer,
  respondHttpRequest,
} from '@/uni_modules/hawkeye-http-server'
// #endif

const id = 'http-demo'
const port = 8080
const contentType = 'application/json; charset=utf-8'
const active = ref(false)
const status = ref('未启动')
const localIpStatus = ref('尚未获取')

const routes = [
  { id: 'list', method: 'GET', path: '/items', statusCode: 200, contentType,
    responseBody: '{"items":[]}', dynamic: false },
  { id: 'item', method: 'GET', path: '/items/:id', statusCode: 200, contentType,
    responseBody: '', dynamic: true },
  { id: 'create', method: 'POST', path: '/items', statusCode: 201, contentType,
    responseBody: '', dynamic: true },
]

function onEvent(event) {
  if (event.type === 'started') {
    status.value = event.data.split('\n').map(host => `http://${host}:${port}`).join('\n')
  }
  if (event.type === 'error' || event.type === 'stopped') {
    active.value = false
    status.value = event.message || '已停止'
  }

  // #ifdef APP-PLUS
  if (event.type !== 'request' || !event.requestId) return
  const params = JSON.parse(event.paramsJson)
  const query = JSON.parse(event.queryJson)
  let statusCode = 200
  let body
  if (event.routeId === 'item') {
    body = { id: params.id, tags: query.tag || [] }
  } else {
    try {
      body = { created: JSON.parse(event.data) }
      statusCode = 201
    } catch {
      statusCode = 400
      body = { error: '请求正文须为 JSON' }
    }
  }
  respondHttpRequest({ id: event.id, requestId: event.requestId, statusCode, contentType,
    body: JSON.stringify(body) })
  // #endif
}

function showLocalIps() {
  // #ifdef APP-PLUS
  if (uni.getSystemInfoSync().platform !== 'android') return
  const addresses = getLocalIpAddresses()
  localIpStatus.value = addresses.length ? addresses.join('\n') : '暂无可用的 IPv4 地址'
  // #endif
}

function start() {
  // #ifdef APP-PLUS
  if (uni.getSystemInfoSync().platform === 'android' && !active.value) {
    active.value = true
    status.value = '正在启动'
    try {
      startHttpServer({ id, port, routes, onEvent })
    } catch (error) {
      active.value = false
      status.value = error.message || '启动失败'
    }
  }
  // #endif
}

function stop() {
  // #ifdef APP-PLUS
  if (active.value) stopHttpServer(id)
  // #endif
}

onHide(stop)
onUnload(stop)
</script>

<style scoped>
.http-demo {
  --demo-ink: #182f29;
  --demo-muted: #4b645a;
  --demo-line: #dbe6e0;
  --demo-tint: #eef5f1;
  box-sizing: border-box;
  min-height: 100vh;
  padding: 20px 16px 24px;
  padding-bottom: calc(24px + env(safe-area-inset-bottom));
  background: #f3f7f4;
  color: var(--demo-ink);
  font-family: Inter, "PingFang SC", "Microsoft YaHei", sans-serif;
}
.demo-shell {
  max-width: 620px;
  margin: 0 auto;
}
.demo-service {
  padding: 20px;
  border-radius: 16px;
  background: #143b34;
  color: #ffffff;
}
.demo-heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px 12px;
}
.demo-title {
  font-size: 24px;
  font-weight: 700;
}
.demo-port {
  padding: 5px 9px;
  border: 1px solid #52786c;
  border-radius: 6px;
  color: #e6f5ed;
  font-size: 13px;
}
.demo-console {
  margin-top: 16px;
  padding: 12px;
  border-left: 3px solid #86cfaf;
  border-radius: 8px;
  background: #0c2c26;
}
.demo-caption {
  display: block;
  margin-bottom: 6px;
  color: #c3dfd4;
  font-size: 12px;
}
.demo-output,
.demo-ip {
  display: block;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  overflow-wrap: anywhere;
  word-break: break-word;
}
.demo-mono {
  font-family: "IBM Plex Mono", Consolas, monospace;
}
.demo-actions {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}
.demo-button {
  box-sizing: border-box;
  min-height: 48px;
  margin: 0;
  padding: 10px 12px;
  border: 1px solid transparent;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  line-height: 1.5;
}
.demo-button::after { border: 0; }
.demo-button:active { opacity: .76; }
.demo-button:focus-visible { outline: 2px solid #278363; outline-offset: 2px; }
.demo-service .demo-button:focus-visible { outline-color: #d8f6e7; }
.demo-actions .demo-button { flex: 1; min-width: 0; }
.demo-start { background: #d8f6e7; color: #12382e; }
.demo-stop { border-color: #719c8d; background: #205044; color: #fff; }
.demo-actions .demo-button[disabled] {
  border-color: #426a5e;
  background: #24483f;
  color: #acc8bc;
}
.demo-panel {
  margin-top: 12px;
  padding: 16px;
  border: 1px solid var(--demo-line);
  border-radius: 12px;
  background: #fff;
}
.demo-panel-title { font-size: 17px; font-weight: 700; }
.demo-lookup { background: var(--demo-tint); color: #1a654f; }
.demo-ip {
  margin-top: 10px;
  padding: 10px 12px;
  border-radius: 8px;
  background: var(--demo-tint);
  color: var(--demo-ink);
}
.demo-route {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
  border-bottom: 1px solid var(--demo-line);
  font-size: 13px;
}
.demo-route:first-of-type { margin-top: 4px; }
.demo-route:last-child { padding-bottom: 0; border-bottom: 0; }
.demo-method {
  flex-shrink: 0;
  min-width: 46px;
  padding: 4px 6px;
  border-radius: 5px;
  background: #e7f4ed;
  color: #1d644c;
  text-align: center;
  font-weight: 700;
}
.demo-method-write { background: #f9eedb; color: #75460b; }
.demo-path { flex: 1; min-width: 0; overflow-wrap: anywhere; word-break: break-word; }
.demo-mode { flex-shrink: 0; color: var(--demo-muted); font-size: 12px; }
@media (max-width: 360px) {
  .http-demo { padding-right: 12px; padding-left: 12px; }
  .demo-service { padding: 16px; }
}
</style>

点击「获取本机 IP」可在启动服务前查看手机地址。服务启动后,可以用局域网内的电脑发送请求。把示例 IP 换成页面显示的手机地址。

curl 'http://192.168.1.20:8080/items'
curl 'http://192.168.1.20:8080/items/42?tag=a&tag=b'
curl -X POST 'http://192.168.1.20:8080/items' -H 'Content-Type: application/json' -d '{"name":"demo"}'

第二条请求会得到 {"id":"42","tags":["a","b"]}。

插件接口

函数 用途
getLocalIpAddresses() 同步返回 string[],包含当前启用的非回环网络接口的 IPv4 地址。服务启动前即可调用。无可用地址或系统限制访问时返回 []。
startHttpServer({ id, port, routes, onEvent }) 启动监听。id 是调用方指定的服务标识,port 范围是 1–65535。在一次前台会话中复用同一个 onEvent 函数。
stopHttpServer(id) 停止对应的服务。收到 stopped 后可再次启动。
respondHttpRequest({ id, requestId, statusCode, contentType, body }) 回应一条动态请求,body 为 UTF-8 文本。返回 true 表示插件接受了响应。请求超时、服务停止、请求已回应或参数无效时返回 false。

路由配置字段

routes 是传给 startHttpServer() 的路由数组,每次可配置 1 到 32 条。每条路由填写下表的七个字段。

字段 类型与取值 用途
id 非空字符串,最多 128 个字符,同一数组内唯一 路由标识。例如填 detail,命中这条路由时 event.routeId 就是 detail。event.id 标识整个服务,event.requestId 标识某一次动态请求。
method 大写字符串,支持 GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS 和 path 一起决定请求命中哪条路由。例如同一个 /items 可以分别配置 GET 和 POST。
path 以 / 开头的路径字符串,最多 256 个字符 固定路径可以写 /health。变量路径段用 :参数名,例如 /items/:id。参数名可以使用英文字母、数字和下划线,首字符使用字母或下划线。查询字符串写在调用地址中。
statusCode 200 到 599 的整数 dynamic: false 时,这是实际返回的 HTTP 状态码。例如 200 表示成功,201 表示已创建。dynamic: true 时仍需填写有效值,实际返回的状态码由 respondHttpRequest() 决定。
contentType Content-Type 字符串,例如 application/json; charset=utf-8、text/plain; charset=utf-8 固定路由用它设置响应头。动态路由在 respondHttpRequest() 中填写本次响应的 Content-Type。
responseBody 字符串,最多 64 KiB(UTF-8) 固定路由按原有文本发送正文。JSON 对象可先用 JSON.stringify() 转为字符串。动态路由通常在这里填 '',实际正文由 respondHttpRequest() 的 body 提供。状态码 204、205、304 使用空正文。
dynamic 布尔值 true 或 false false 使用本行配置直接响应。true 会在 request 事件中给出 requestId,供 JS 读取参数和正文,再调用 respondHttpRequest()。等待 15 秒超时后返回 504。

Vue 2 示例中的三条路由

  • health 配置了 GET /health 和 dynamic: false。访问后直接得到 200 和 {"ok":true}。

  • detail 配置了 GET /items/:id 和 dynamic: true。访问 /items/42?tag=a&tag=b 时,从 JSON.parse(event.paramsJson).id 取得字符串 "42",从 JSON.parse(event.queryJson).tag 取得 ['a', 'b']。

  • create 配置了 POST /items 和 dynamic: true。请求正文通过 event.data 传入;示例解析 JSON 后,在 respondHttpRequest() 中设置 statusCode: 201,并传回生成的正文。

  • :id 匹配一个非空路径段。相同请求方法下优先匹配更具体的路径,例如 /items/latest 优先于 /items/:id。同一方法下 /items/:id 和 /items/:code 是重复规则。HEAD 找不到对应路由时使用匹配的 GET 路由并省略响应正文。

  • 查询字符串在路径匹配后单独解析。paramsJson 是路径参数对象,例如 {"id":"42"}。queryJson 的每个值都是字符串数组,例如 {"tag":["a","b"],"page":["2"]}。参数值会进行 URL 解码,查询字符串中的 + 表示空格。

  • 找不到路径时返回 404。路径匹配但请求方法不符时返回 405,响应头 Allow 列出支持的方法。

  • 每次可启动一个监听服务,最多 8 个同时连接。请求正文使用 Content-Length,最多 64 KiB。

HTTP 服务事件

onEvent 类型 字段说明
started id 为服务标识。data 以 127.0.0.1 开头,后面是启动时取得的非回环 IPv4 地址,各地址用换行分隔。
request method、path、remoteAddress、routeId、paramsJson 和 queryJson 描述该请求。固定响应的 statusCode 为响应状态,data 是正文预览。动态请求带有 requestId,statusCode 为 0,data 为完整正文。
response 动态响应处理完成后提供 requestId 和最终 statusCode,便于记录结果。
stopped 服务已停止,可以重新启动监听。
error 启动或监听失败,message 包含错误原因。

路由在启动时加载。修改监听端口或路由后,停止服务再重新启动。页面离开和 App 切到后台可通过对应的 onHide 调用 stopHttpServer。

隐私、权限声明

1. 本插件需要申请的系统权限列表:

无

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

不采集

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

无

暂无用户评论。