HTTP 请求(wad.http.*)
面板与逻辑层可用。面板侧由宿主代理转发 —— 没有 CORS,没有页面域名限制;逻辑层走 wx.request。
API
| 方法 | 签名 | 返回 |
|---|---|---|
wad.http.get | get(url, opts?) → Promise<string> | 响应体;非 2xx reject |
wad.http.post | post(url, body?, opts?) → Promise<string> | 同上 |
wad.http.request | request(method, url, body?, opts?) → Promise<string> | GET / POST |
wad.http.raw | raw(method, url, body?, opts?) → Promise<Raw> | 完整响应,非 2xx 不抛错 |
opts.headers 传自定义请求头。Raw 结构:
js
{ status: 200, headers: { ... }, body: '...', truncated: false }基本用法
js
// 只关心 body(非 2xx 会 reject)
const text = await wad.http.get('https://httpbin.org/get');
const out = await wad.http.post('https://httpbin.org/post', JSON.stringify({ a: 1 }));
// 带请求头
const data = await wad.http.get('https://api.example.com/v1/me', {
headers: { Authorization: 'Bearer ' + token }
});需要状态码时用 raw
js
const r = await wad.http.raw('GET', 'https://api.example.com/may-404');
if (r.status === 200) {
handle(r.body);
} else if (r.status === 429) {
wad.ui.toast('限流了,稍后再试');
} else {
wad.log('HTTP ' + r.status, r.body.slice(0, 200));
}带取消的轮询
js
let stopped = false;
wad.on('detach', function () { stopped = true; });
(function poll() {
if (stopped) return;
wad.http.raw('GET', 'https://api.example.com/status').then(function (r) {
if (r.status === 200) render(JSON.parse(r.body));
}).catch(function (e) {
wad.log('poll fail', e.message);
}).then(function () {
if (!stopped) setTimeout(poll, 5000);
});
})();注意
- 响应体超过总线单帧上限(200 KB)时
truncated: true,大文件请走net.body(id)或分段接口; - 面板侧请求经过宿主网络栈,宿主开启捕获时这些请求也会被自己捕获;
- 不要在面板里直接
fetch()第三方域名 —— 那是页面的 CORS 语义;用wad.http.*。