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 参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
port | number | 是 | 端口号(1-65535) |
rootPath | string | 否 | 静态文件根目录 |
allowCors | boolean | 否 | 是否允许跨域 |
proxyEnabled | boolean | 否 | 是否启用代理转发 |
proxyRules | ProxyRule[] | 否 | 代理规则列表 |
ProxyRule
| 字段 | 类型 | 说明 |
|---|---|---|
path | string | 代理路径前缀,如 /api |
target | string | 目标服务器地址 |
method | string | 请求方法(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 自动检测,控制台会输出访问地址