advanced-demo.html 21.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GLSK-Fetch 高级功能演示</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
      line-height: 1.6;
    }
    h1, h2, h3 {
      color: #333;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }
    .section {
      margin-bottom: 30px;
      padding: 20px;
      border-radius: 5px;
      background-color: #f9f9f9;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    pre {
      background-color: #f5f5f5;
      padding: 15px;
      border-radius: 5px;
      overflow-x: auto;
    }
    code {
      font-family: Consolas, Monaco, 'Andale Mono', monospace;
      font-size: 14px;
    }
    button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 10px 15px;
      margin: 10px 5px 10px 0;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    button:hover {
      background-color: #45a049;
    }
    .error-btn {
      background-color: #f44336;
    }
    .warning-btn {
      background-color: #ff9800;
    }
    .result {
      background-color: #fff;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 15px;
      margin-top: 10px;
      min-height: 100px;
      max-height: 300px;
      overflow-y: auto;
      white-space: pre-wrap;
      word-break: break-all;
    }
    .tabs {
      display: flex;
      border-bottom: 1px solid #ddd;
      margin-bottom: 20px;
    }
    .tab {
      padding: 10px 20px;
      cursor: pointer;
      border: 1px solid transparent;
      border-bottom: none;
      margin-bottom: -1px;
      border-radius: 4px 4px 0 0;
    }
    .tab:hover {
      background-color: #f5f5f5;
    }
    .tab.active {
      background-color: #fff;
      border-color: #ddd;
      border-bottom-color: #fff;
    }
    .tab-content {
      display: none;
    }
    .tab-content.active {
      display: block;
    }
    .loader {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 3px solid rgba(0,0,0,0.1);
      border-radius: 50%;
      border-top-color: #4CAF50;
      animation: spin 1s ease-in-out infinite;
      margin-left: 10px;
      vertical-align: middle;
    }
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    .hidden {
      display: none;
    }
  </style>
</head>
<body>
  <h1>GLSK-Fetch 高级功能演示</h1>
  
  <div class="tabs">
    <div class="tab active" data-tab="cancel">取消请求</div>
    <div class="tab" data-tab="signature">请求签名</div>
    <div class="tab" data-tab="custom-signature">自定义签名</div>
    <div class="tab" data-tab="custom-options">自定义选项</div>
    <div class="tab" data-tab="events">事件订阅</div>
  </div>
  
  <!-- 取消请求 -->
  <div id="cancel" class="tab-content active">
    <div class="section">
      <h2>取消请求示例</h2>
      <p>演示如何创建可取消的请求并在需要时取消它们</p>
      
      <pre><code>// 创建请求实例
const request = new Request({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 5000
});

// 发送可取消的GET请求
const getRequest = request.get('/posts/1');

// 请求可以通过abort方法取消
getRequest.abort();

// 发送可取消的POST请求
const postRequest = request.post('/posts', {
  data: { title: 'foo', body: 'bar', userId: 1 }
});

// 请求可以通过abort方法取消
postRequest.abort();</code></pre>
      
      <div>
        <button id="longGetBtn">发送长时间GET请求</button>
        <button id="cancelGetBtn" class="error-btn">取消GET请求</button>
        <div id="getLoader" class="loader hidden"></div>
      </div>
      
      <div>
        <button id="longPostBtn">发送长时间POST请求</button>
        <button id="cancelPostBtn" class="error-btn">取消POST请求</button>
        <div id="postLoader" class="loader hidden"></div>
      </div>
      
      <h3>结果:</h3>
      <div id="cancelResult" class="result">请点击按钮发送请求...</div>
    </div>
  </div>
  
  <!-- 请求签名 -->
  <div id="signature" class="tab-content">
    <div class="section">
      <h2>默认请求签名示例</h2>
      <p>演示如何使用默认签名功能发送带签名的请求</p>
      
      <pre><code>// 创建带签名的请求实例
const requestWithSignature = new Request({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  appId: 'your-app-id',
  appSecret: 'your-app-secret'
});

// 发送带签名的GET请求
requestWithSignature.get('/data', {
  params: { id: 123 }
});

// 发送带签名的POST请求
requestWithSignature.post('/data', {
  data: { name: 'test', value: 456 }
});</code></pre>
      
      <div>
        <button id="signatureGetBtn">发送带签名的GET请求</button>
        <button id="signaturePostBtn">发送带签名的POST请求</button>
      </div>
      
      <h3>结果:</h3>
      <div id="signatureResult" class="result">请点击按钮发送请求...</div>
    </div>
  </div>
  
  <!-- 自定义签名 -->
  <div id="custom-signature" class="tab-content">
    <div class="section">
      <h2>自定义签名示例</h2>
      <p>演示如何使用自定义签名函数发送请求</p>
      
      <pre><code>// 自定义签名函数
function customSignature(options) {
  const { appId, appSecret, timestamp, nonce, data } = options;
  
  // 自定义签名逻辑
  const signStr = `${appId}${appSecret}${timestamp}${nonce}${JSON.stringify(data || {})}`;
  const sign = sha256(signStr);
  
  return {
    appId,
    timestamp,
    nonce,
    sign
  };
}

// 创建带自定义签名的请求实例
const requestWithCustomSignature = new Request({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  appId: 'your-app-id',
  appSecret: 'your-app-secret',
  signatureFunc: customSignature
});</code></pre>
      
      <div>
        <button id="customSignatureGetBtn">发送自定义签名GET请求</button>
        <button id="customSignaturePostBtn">发送自定义签名POST请求</button>
      </div>
      
      <h3>结果:</h3>
      <div id="customSignatureResult" class="result">请点击按钮发送请求...</div>
    </div>
  </div>
  
  <!-- 自定义选项 -->
  <div id="custom-options" class="tab-content">
    <div class="section">
      <h2>自定义httpOptions.customer示例</h2>
      <p>演示如何使用自定义httpOptions.customer选项</p>
      
      <pre><code>// 创建带自定义选项的请求实例
const requestWithCustomOptions = new Request({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 5000,
  httpOptions: {
    customer: {
      // 自定义选项
      customField1: 'value1',
      customField2: 'value2',
      responseType: 'json'
    }
  }
});</code></pre>
      
      <div>
        <button id="customOptionsGetBtn">发送自定义选项GET请求</button>
        <button id="customOptionsPostBtn">发送自定义选项POST请求</button>
      </div>
      
      <h3>结果:</h3>
      <div id="customOptionsResult" class="result">请点击按钮发送请求...</div>
    </div>
  </div>
  
  <!-- 事件订阅 -->
  <div id="events" class="tab-content">
    <div class="section">
      <h2>初始化时订阅事件示例</h2>
      <p>演示如何在初始化时订阅请求事件</p>
      
      <pre><code>// 创建带事件订阅的请求实例
const requestWithEvents = new Request({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 5000,
  events: {
    request: (config) => {
      console.log('请求开始:', config);
    },
    response: (response) => {
      console.log('请求成功:', response);
    },
    error: (error) => {
      console.error('请求失败:', error);
    }
  }
});</code></pre>
      
      <div>
        <button id="eventsGetBtn">发送带事件的GET请求</button>
        <button id="eventsPostBtn">发送带事件的POST请求</button>
        <button id="eventsErrorBtn" class="warning-btn">发送错误请求</button>
      </div>
      
      <h3>结果:</h3>
      <div id="eventsResult" class="result">请点击按钮发送请求...</div>
    </div>
  </div>

  <!-- 引入库文件 -->
  <script src="../dist/index.umd.js"></script>
  
  <script>
    // 获取DOM元素
    function $(id) {
      return document.getElementById(id);
    }
    
    // 设置标签页切换
    document.querySelectorAll('.tab').forEach(tab => {
      tab.addEventListener('click', () => {
        // 移除所有活动标签和内容
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        
        // 激活当前标签和内容
        tab.classList.add('active');
        const tabId = tab.getAttribute('data-tab');
        $(tabId).classList.add('active');
      });
    });
    
    // 检查库是否正确加载
    console.log('Library loaded:', window.GlskFetch || window.glskFetch);
    
    // 获取库引用
    const glskFetch = window.GlskFetch || window.glskFetch || {};
    const Request = glskFetch.default || glskFetch;
    
    // 简单的SHA-256实现(仅用于演示)
    async function sha256(message) {
      const msgBuffer = new TextEncoder().encode(message);
      const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }
    
    // 模拟延迟
    function delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    // 创建基本请求实例
    const baseRequest = new Request({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 10000
    });
    https://jsonplaceholder.typicode.com?id=1&method=xxx.xxx.ccc.bbb&sdctag=true
    // 添加请求拦截器
    baseRequest.interceptors.request.use(
      (config) => {
        console.log('请求拦截器:', config);
        return config;
      }
    );
    
    // 添加响应拦截器
    baseRequest.interceptors.response.use(
      (response) => {
        console.log('响应拦截器:', response);
        return response;
      },
      (error) => {
        console.error('响应错误拦截器:', error);
        return Promise.reject(error);
      }
    );
    
    // ===== 取消请求示例 =====
    let currentGetRequest = null;
    let currentPostRequest = null;
    
    $('longGetBtn').addEventListener('click', () => {
      // 如果已有请求,先取消
      if (currentGetRequest) {
        currentGetRequest.abort();
      }
      
      $('getLoader').classList.remove('hidden');
      $('cancelResult').textContent = '正在发送长时间GET请求...';
      
      // 发送新请求
      currentGetRequest = baseRequest.get('/posts/1');
      
      currentGetRequest
        .then(response => {
          $('cancelResult').textContent = 'GET请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          if (error.isCancel) {
            $('cancelResult').textContent = 'GET请求已取消';
          } else {
            $('cancelResult').textContent = 'GET请求错误: ' + error.message;
          }
        })
        .finally(() => {
          $('getLoader').classList.add('hidden');
          currentGetRequest = null;
        });
    });
    
    $('cancelGetBtn').addEventListener('click', () => {
      if (currentGetRequest) {
        currentGetRequest.abort();
        $('cancelResult').textContent = '正在取消GET请求...';
      } else {
        $('cancelResult').textContent = '没有正在进行的GET请求可取消';
      }
    });
    
    $('longPostBtn').addEventListener('click', () => {
      // 如果已有请求,先取消
      if (currentPostRequest) {
        currentPostRequest.abort();
      }
      
      $('postLoader').classList.remove('hidden');
      $('cancelResult').textContent = '正在发送长时间POST请求...';
      
      // 发送新请求
      currentPostRequest = baseRequest.post('/posts', {
        title: '测试文章',
        body: '这是一篇测试文章',
        userId: 1
      });
      
      currentPostRequest
        .then(response => {
          $('cancelResult').textContent = 'POST请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          if (error.isCancel) {
            $('cancelResult').textContent = 'POST请求已取消';
          } else {
            $('cancelResult').textContent = 'POST请求错误: ' + error.message;
          }
        })
        .finally(() => {
          $('postLoader').classList.add('hidden');
          currentPostRequest = null;
        });
    });
    
    $('cancelPostBtn').addEventListener('click', () => {
      if (currentPostRequest) {
        currentPostRequest.abort();
        $('cancelResult').textContent = '正在取消POST请求...';
      } else {
        $('cancelResult').textContent = '没有正在进行的POST请求可取消';
      }
    });
    
    // ===== 默认签名示例 =====
    const requestWithSignature = new Request({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 5000,
      appId: 'test-app-id',
      appSecret: 'test-app-secret'
    });
    
    // 添加拦截器显示签名信息
    requestWithSignature.interceptors.response.use(
      (response) => {
        // 获取签名信息
        const signInfo = response.config.headers ? (response.config.headers['X-Signature'] || '未找到签名') : '未找到签名';
        console.log('签名信息:', signInfo);
        
        // 为了演示,在响应中添加签名信息
        response.data.signatureInfo = signInfo;
        
        return response;
      }
    );
    
    $('signatureGetBtn').addEventListener('click', () => {
      $('signatureResult').textContent = '正在发送带签名的GET请求...';
      
      requestWithSignature.get('/posts/1', {
        params: { userId: 1 }
      })
        .then(response => {
          $('signatureResult').textContent = 'GET请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('signatureResult').textContent = 'GET请求错误: ' + error.message;
        });
    });
    
    $('signaturePostBtn').addEventListener('click', () => {
      $('signatureResult').textContent = '正在发送带签名的POST请求...';
      
      requestWithSignature.post('/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1
      })
        .then(response => {
          $('signatureResult').textContent = 'POST请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('signatureResult').textContent = 'POST请求错误: ' + error.message;
        });
    });
    
    // ===== 自定义签名示例 =====
    // 自定义签名函数
    async function customSignature(options) {
      const { appId, appSecret, timestamp, nonce, data } = options;
      
      // 自定义签名逻辑
      const signStr = `${appId}${appSecret}${timestamp}${nonce}${JSON.stringify(data || {})}`;
      const sign = await sha256(signStr);
      
      return {
        appId,
        timestamp,
        nonce,
        sign,
        signMethod: 'custom-sha256'
      };
    }
    
    // 创建带自定义签名的请求实例
    const requestWithCustomSignature = new Request({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 5000,
      appId: 'custom-app-id',
      appSecret: 'custom-app-secret',
      signatureFunc: customSignature
    });
    
    // 添加拦截器显示签名信息
    requestWithCustomSignature.interceptors.response.use(
      (response) => {
        // 获取签名信息
        const signInfo = response.config.headers ? (response.config.headers['X-Signature'] || '未找到签名') : '未找到签名';
        console.log('自定义签名信息:', signInfo);
        
        // 为了演示,在响应中添加签名信息
        response.data.signatureInfo = signInfo;
        response.data.signatureType = 'custom';
        
        return response;
      }
    );
    
    $('customSignatureGetBtn').addEventListener('click', () => {
      $('customSignatureResult').textContent = '正在发送自定义签名GET请求...';
      
      requestWithCustomSignature.get('/posts/2', {
        params: { userId: 1 }
      })
        .then(response => {
          $('customSignatureResult').textContent = 'GET请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('customSignatureResult').textContent = 'GET请求错误: ' + error.message;
        });
    });
    
    $('customSignaturePostBtn').addEventListener('click', () => {
      $('customSignatureResult').textContent = '正在发送自定义签名POST请求...';
      
      requestWithCustomSignature.post('/posts', {
        title: 'custom title',
        body: 'custom body content',
        userId: 2
      })
        .then(response => {
          $('customSignatureResult').textContent = 'POST请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('customSignatureResult').textContent = 'POST请求错误: ' + error.message;
        });
    });
    
    // ===== 自定义选项示例 =====
    // 创建带自定义选项的请求实例
    const requestWithCustomOptions = new Request({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 5000,
      httpOptions: {
        customer: {
          // 自定义选项
          customField1: 'value1',
          customField2: 'value2',
          responseType: 'json'
        }
      }
    });
    
    // 添加拦截器显示自定义选项
    requestWithCustomOptions.interceptors.response.use(
      (response) => {
        // 添加自定义选项信息到响应
        response.data.customOptions = response.config.httpOptions ? response.config.httpOptions.customer : '未找到自定义选项';
        return response;
      }
    );
    
    $('customOptionsGetBtn').addEventListener('click', () => {
      $('customOptionsResult').textContent = '正在发送自定义选项GET请求...';
      
      requestWithCustomOptions.get('/posts/3', {
        params: { userId: 1 }
      })
        .then(response => {
          $('customOptionsResult').textContent = 'GET请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('customOptionsResult').textContent = 'GET请求错误: ' + error.message;
        });
    });
    
    $('customOptionsPostBtn').addEventListener('click', () => {
      $('customOptionsResult').textContent = '正在发送自定义选项POST请求...';
      
      requestWithCustomOptions.post('/posts', {
        title: 'options title',
        body: 'options body content',
        userId: 3
      })
        .then(response => {
          $('customOptionsResult').textContent = 'POST请求成功:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('customOptionsResult').textContent = 'POST请求错误: ' + error.message;
        });
    });
    
    // ===== 事件订阅示例 =====
    // 创建带事件订阅的请求实例
    const requestWithEvents = new Request({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 5000,
      events: {
        request: (config) => {
          console.log('请求开始:', config);
          $('eventsResult').textContent += '\n请求开始: ' + config.method + ' ' + config.url;
        },
        response: (response) => {
          console.log('请求成功:', response);
          $('eventsResult').textContent += '\n请求成功: 状态码 ' + response.status;
        },
        error: (error) => {
          console.error('请求失败:', error);
          $('eventsResult').textContent += '\n请求失败: ' + error.message;
        }
      }
    });
    
    $('eventsGetBtn').addEventListener('click', () => {
      $('eventsResult').textContent = '正在发送带事件的GET请求...';
      
      requestWithEvents.get('/posts/4', {
        params: { userId: 1 }
      })
        .then(response => {
          $('eventsResult').textContent += '\nGET请求完成,响应数据:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('eventsResult').textContent += '\nGET请求处理错误: ' + error.message;
        });
    });
    
    $('eventsPostBtn').addEventListener('click', () => {
      $('eventsResult').textContent = '正在发送带事件的POST请求...';
      
      requestWithEvents.post('/posts', {
        title: 'event title',
        body: 'event body content',
        userId: 4
      })
        .then(response => {
          $('eventsResult').textContent += '\nPOST请求完成,响应数据:\n' + JSON.stringify(response.data, null, 2);
        })
        .catch(error => {
          $('eventsResult').textContent += '\nPOST请求处理错误: ' + error.message;
        });
    });
    
    $('eventsErrorBtn').addEventListener('click', () => {
      $('eventsResult').textContent = '正在发送错误请求...';
      
      // 创建一个会失败的请求
      requestWithEvents.get('/posts/999', {
        timeout: 100  // 设置超短超时时间
      })
        .then(response => {
          $('eventsResult').textContent += '\n请求不应该成功';
        })
        .catch(error => {
          $('eventsResult').textContent += '\n请求预期失败: ' + error.message;
        });
    });
  </script>
</body>
</html>