whitelist-simple-test.html 8.8 KB
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>白名单URL简单测试</title>
  <script src="../dist/index.umd.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }

    .container {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .card {
      border: 1px solid #ddd;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    pre {
      background-color: #f5f5f5;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
    }

    button {
      padding: 8px 16px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-right: 10px;
      margin-bottom: 10px;
    }

    button:hover {
      background-color: #45a049;
    }
  </style>
</head>

<body>
  <h1>白名单URL简单测试</h1>

  <div class="container">
    <div class="card">
      <h2>测试说明</h2>
      <p>本页面测试在请求前检查method参数是否在白名单中,如果在白名单中,则在URL中添加sdctag=true参数并参与签名。</p>
      <button id="testWhitelist">测试GET请求</button>
      <button id="testNonWhitelist">测试POST请求</button>
      <button id="testNoRetryError">测试无重试的错误事件</button>
      <h3>结果:</h3>
      <pre id="result">点击按钮开始测试...</pre>
    </div>
  </div>

  <script>
    // 等待页面加载完成
    document.addEventListener('DOMContentLoaded', function () {
      // 获取DOM元素
      const resultElement = document.getElementById('result');
      const testWhitelistButton = document.getElementById('testWhitelist');
      const testNonWhitelistButton = document.getElementById('testNonWhitelist');
      const testNoRetryErrorButton = document.getElementById('testNoRetryError');
       let id = null;
      setTimeout(() => {
        id = 'dj-wechat-dd8da2bb-3b5e-491d-9df5-2ba33b1a3849-rop';
      }, 1000);
      setTimeout(() => {
        id = 'dj-wechat-dd8da2bb-3b5e-491d-9df5-2ba33b1a3849-rop';
      }, 2000);
      // 检查GlskToolkit对象
      console.log('GlskToolkit:', window.GlskToolkit);
        // 从命名导出中获取Request构造函数
      const Request = window.GlskToolkit?.Request;
      // 注意:Trace对象在UMD模块中可能不可直接访问
      // 但Request类内部已经正确引入并使用了Trace对象
      // 所以白名单功能应该能正常工作
      console.log('SDK内部已集成Trace模块,将从服务器获取白名单URL');

      // 创建请求实例
      const request = new Request({
        baseURL: 'http://192.168.1.117:9898/gsc-vcp-web-facade',
        appId: 'Web_DJia',
        appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
        timeout:5000,
        sentry: {
          enable: false,
          dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1'
        },
        session: {
          sessionId: ()=>id,
          requiresSession: true
        },
        security: { 
          enable: false,
          address: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common' // 自定义地址
        },
        response: {
          code_key: 'code',           // 或者你后台实际使用的状态码字段名
          code_success_value: '0',
          data_key: 'data',
          errId: 'errId',
          errId_logout_value: '21'
        },
        events:{
          response: (responseData, config) => {
            throw new Error("response事件触发");
            console.log('%c📥 response事件触发', 'color: #4CAF50; font-weight: bold;', responseData, config);
          },
          error: (error, config) => {
            console.log('%c❌ error事件触发', 'color: #F44336; font-weight: bold;', error, config);
          },
          request: (request, config) => {
            console.log('%c📤 request事件触发', 'color: #2196F3; font-weight: bold;', request, config);
          },
          logout: (data,config) => {
            console.log('%c🚪 logout事件触发', 'color: #FF9800; font-weight: bold;', config);
          },
          duplicate: (url, config) => {
            console.log('%c🚫 duplicate事件触发', 'color: #9C27B0; font-weight: bold;', url, config);
          }
        }
      });

      // request.interceptors.response.use(
      //   response => {
      //     console.log('%c📥 response事件触发', 'color: #4CAF50; font-weight: bold;', response, response.config);
      //     // 对响应数据做点什么
      //     return response;
      //   },
      //   error => {
      //     console.log('%c❌ error事件触发', 'color: #F44336; font-weight: bold;', error, error.config);
      //     // 对响应错误做点什么
      //     return Promise.reject(error);
      //   }
      // );

      // 测试白名单内请求
      testWhitelistButton.addEventListener('click', async function () {
        resultElement.textContent = '请求中...';
        try {
          // 白名单URL列表由SDK内部处理
          // 我们只需要在请求参数中添加method参数
          // console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');

          // 使用params包裹GET请求参数
          const result = await request.get('/test/param/test', {
            params:{
            "id":6,
            "test":"test",
            "objs": ["hehe", "haah"],
            "dogs":[{"name":"haogou","age":1},{"name":"拉布拉多","age":2}],
             "dogs":{"name":"haogou","age":1},
             "X-Mock":false
        },
        retry:{
          retries: 3,
          retryDelay: 1000,
        }
          });
         
          resultElement.textContent =
            `请求成功:\n请求参数: ${JSON.stringify(result.config.data, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
        } catch (error) {
          resultElement.textContent = `请求失败: ${error.message}`;
        }
      });

      // 测试白名单外请求
      testNonWhitelistButton.addEventListener('click', async function () {
        resultElement.textContent = '请求中...';
        try {
          // 白名单URL列表由SDK内部处理
          // 我们只需要在请求参数中添加method参数
          // console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request);
          
          // POST请求使用data传递参数(放在请求体中)
          const result = await request.post('/test/param/test', 
            // 请求体数据
            {
              endTime: "2025-01-01",
              merchantNos: ["44211470"],
              startTime: "2024-01-01",
              type: 1
            }, {
                    duplicatePrevention: true,  // 简化配置:直接传入 true
                    retry:{
                    retries: 3,
                    retryDelay: 1000,
                    returnAll:true
                  },
                  noSignAttr:['endTime','merchantNos']
                }
          );
          // console.log("🚀 ~ result:", result)
          resultElement.textContent =
            `请求成功 响应数据: ${JSON.stringify(result, null, 2)}`;
        } catch (error) {
          resultElement.textContent = `请求失败: ${error.message}`;
        }
      });

      // 测试无重试的错误事件
      testNoRetryErrorButton.addEventListener('click', async function () {
        resultElement.textContent = '请求中...';
        try {
          // 白名单URL列表由SDK内部处理
          // 我们只需要在请求参数中添加method参数
          // console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request);
          
          // POST请求使用data传递参数(放在请求体中)
          const result = await request.request(
            {
              method:'POST',
              url:'/test/param/test',
              data:{
              endTime: "2025-01-01",
              merchantNos: ["44211470"],
              startTime: "2024-01-01",
              type: 1,
              test:undefined
            }, 
              duplicatePrevention: true,  // 简化配置:直接传入 true
              retry:{
              retries: 1,
              retryDelay: 1000,
            },
            returnAll:false
            // noSignAttr:['endTime','merchantNos']
            },
          );
          console.log("🚀 ~ result:", result)
          resultElement.textContent =
            `请求成功 响应数据: ${JSON.stringify(result, null, 2)}`;
        } catch (error) {
          resultElement.textContent = `请求失败: ${error.message}`;
        }
      });
    });
  </script>
</body>

</html>