abort-demo.html 6.21 KB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Abort 手动中止请求演示</title>
  <style>
    :root { color-scheme: light dark; }
    body {
      font-family: Arial, sans-serif;
      max-width: 900px;
      margin: 0 auto;
      padding: 24px;
      line-height: 1.6;
      background: #f6f7f9;
    }
    h1 { margin: 0 0 8px; }
    .subtitle { color: #666; margin-bottom: 20px; }
    .card {
      background: #fff;
      border-radius: 10px;
      padding: 16px 18px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.06);
      margin-bottom: 16px;
    }
    .row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
    button {
      background: #2563eb;
      color: #fff;
      border: none;
      padding: 10px 16px;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
    }
    button.secondary { background: #64748b; }
    button.danger { background: #dc2626; }
    button:disabled { opacity: 0.6; cursor: not-allowed; }
    .status {
      display: inline-flex; align-items: center; gap: 8px;
      padding: 6px 10px; border-radius: 6px; font-size: 13px; background: #eef2ff; color: #1e40af;
    }
    .status.error { background: #fee2e2; color: #991b1b; }
    .status.success { background: #dcfce7; color: #14532d; }
    .log { white-space: pre-wrap; word-break: break-word; background:#0b1021; color:#d1d5db; padding:12px; border-radius:8px; min-height: 120px; }
    .muted { color: #6b7280; font-size: 13px; }
    .kv { display:grid; grid-template-columns: 140px 1fr; gap:8px 12px; }
    code { background:#f1f5f9; padding:2px 6px; border-radius:4px; }
  </style>
</head>
<body>
  <h1>Abort 手动中止请求演示</h1>
  <div class="subtitle">演示在 Web 端使用 Request + AbortController 主动中止一个耗时请求(基于 httpbin 延迟接口)。</div>

  <div class="card">
    <div class="kv">
      <div>请求地址</div>
      <div><code>https://httpbin.org/delay/10</code>(10 秒延迟)</div>
      <div>发起方式</div>
      <div>通过库的 <code>Request.get</code>,传入 <code>signal</code>(BaseAdapter 会合并/联动)</div>
    </div>
  </div>

  <div class="card">
    <div class="row" style="margin-bottom:10px;">
      <button id="btnStart">发起耗时请求</button>
      <button id="btnAbort" class="danger" disabled>立即中止</button>
      <button id="btnReset" class="secondary">重置</button>
      <span id="status" class="status">空闲中</span>
    </div>
    <div class="muted">提示:点击“发起耗时请求”后,立刻或数秒后点击“立即中止”,应当捕获到 AbortError 或等价错误;若不中止,约 10 秒后返回成功。</div>
  </div>

  <div class="card">
    <h3 style="margin-top:0;">日志</h3>
    <div id="log" class="log"></div>
  </div>

  <script type="module">
    import { Request } from '../dist/index.esm.js';

    const request = new Request({
      baseURL: 'https://httpbin.org',
      timeout: 0, // 不设置库内超时,让演示专注于手动 abort(0 或不填表示不超时,依实现而定)
    });

    const el = {
      btnStart: document.getElementById('btnStart'),
      btnAbort: document.getElementById('btnAbort'),
      btnReset: document.getElementById('btnReset'),
      status: document.getElementById('status'),
      log: document.getElementById('log')
    };

    let controller = null;
    let running = false;
    let startedAt = 0;
    let timer = null;

    function setStatus(text, cls = '') {
      el.status.textContent = text;
      el.status.className = 'status' + (cls ? ' ' + cls : '');
    }
    function appendLog(line) {
      const ts = new Date().toISOString().substring(11, 19);
      el.log.textContent += `[${ts}] ${line}\n`;
      el.log.scrollTop = el.log.scrollHeight;
    }
    function reset() {
      if (timer) { clearInterval(timer); timer = null; }
      controller = null; running = false; startedAt = 0;
      el.btnStart.disabled = false;
      el.btnAbort.disabled = true;
      setStatus('空闲中');
      appendLog('--- 已重置 ---');
    }

    async function startRequest() {
      if (running) return;
      running = true;
      controller = new AbortController();
      startedAt = Date.now();
      setStatus('请求进行中...');
      el.btnStart.disabled = true;
      el.btnAbort.disabled = false;
      appendLog('开始请求 /delay/10');

      // 展示经过时间(秒)
      timer = setInterval(() => {
        const s = ((Date.now() - startedAt) / 1000).toFixed(1);
        setStatus(`请求进行中... 已用时 ${s}s`);
      }, 200);

      try {
        const res = await request.get('/delay/10', {
          // 关键:传入外部 AbortController.signal
          signal: controller.signal,
          // 演示为纯粹的手动中止,不设置 retry 等其他功能,避免干扰判断
        });
        clearInterval(timer); timer = null;
        setStatus('请求成功', 'success');
        appendLog('✓ 成功返回,示例响应字段:' + JSON.stringify({ url: res?.data?.url, origin: res?.data?.origin }));
      } catch (err) {
        clearInterval(timer); timer = null;
        const aborted = controller?.signal?.aborted;
        const name = err?.name || 'Error';
        const msg = err?.message || String(err);
        if (aborted || name === 'AbortError') {
          setStatus('已中止(Abort)', 'error');
          appendLog(`✗ 请求被中止:name=${name}, message=${msg}`);
        } else {
          setStatus('出错', 'error');
          appendLog(`✗ 发生错误:name=${name}, message=${msg}`);
        }
      } finally {
        // 结束态统一关闭按钮状态
        el.btnStart.disabled = false;
        el.btnAbort.disabled = true;
        running = false;
      }
    }

    function doAbort() {
      if (!controller) return;
      appendLog('发出 abort() 信号');
      try { controller.abort('用户主动中止'); } catch {}
    }

    // 事件绑定
    el.btnStart.addEventListener('click', startRequest);
    el.btnAbort.addEventListener('click', doAbort);
    el.btnReset.addEventListener('click', reset);

    // 初始
    reset();
    appendLog('页面已加载,可开始演示。');
  </script>
</body>
</html>