Skip to content

TuiHttpServer

设备端 HTTP 服务器插件,支持 Android、iOS、Harmony

引入

ts
import { httpServer } from '@/uni_modules/tui-http-server'

基础用法

ts
const server = new httpServer()

server.start({
  port: 8080,
  rootPath: httpServer.getStaticPath('static'),
  allowCors: true,
  success: (res) => {
    console.log('服务器已启动:', res.accessUrl)
  }
})

启动后在电脑浏览器访问 http://手机IP:8080/xxx.jpg 即可。

API

class httpServer

实例方法

方法说明
start(options)启动 HTTP 服务器
stop(options)停止服务器
getStatus(options)获取服务器运行状态
addProxyRule(options)添加代理转发规则
removeProxyRule(options)移除代理规则
getProxyRules(options)获取代理规则列表

静态方法

方法说明
getStaticPath(subPath?)获取静态文件存放路径

start 参数

参数类型必填说明
portnumber端口号(1-65535)
rootPathstring静态文件根目录
allowCorsboolean是否允许跨域
proxyEnabledboolean是否启用代理转发
proxyRulesProxyRule[]代理规则列表

ProxyRule

字段类型说明
pathstring代理路径前缀,如 /api
targetstring目标服务器地址
methodstring请求方法(ALL/GET/POST...),默认 ALL

代理转发示例

ts
server.start({
  port: 8080,
  allowCors: true,
  proxyEnabled: true,
  proxyRules: [{
    path: '/api',
    target: 'https://your-backend.com',
    method: 'ALL'
  }]
})

访问 http://手机IP:8080/api/users 会自动转发到 https://your-backend.com/api/users

注意事项

  • Android 端依赖 NanoHTTPD,需要使用自定义基座
  • 静态文件从 rootPath 目录读取
  • IP 自动检测,控制台会输出访问地址