Commit c078e635 by liimin

refactor(request): 添加method参数到签名参数中

refactor(utils): 重构参数处理逻辑,支持多种数组处理模式

refactor(signature): 优化签名生成逻辑,增加参数验证

refactor(adapter): 使用通用参数处理函数重构URL构建逻辑

chore(examples): 移除过时的示例文件
1 parent 04d7d083
<!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>
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>核心功能综合测试</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.test-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
.success { color: green; }
.error { color: red; }
.info { color: blue; }
button { padding: 10px 15px; margin: 5px; cursor: pointer; }
pre { background: #f5f5f5; padding: 10px; border-radius: 3px; overflow-x: auto; }
.result { margin: 10px 0; padding: 10px; background: #f9f9f9; border-radius: 3px; }
</style>
</head>
<body>
<h1>glsk-fetch 核心功能综合测试</h1>
<div class="test-section">
<h2>1. 模块加载测试</h2>
<button onclick="testModuleLoading()">测试模块加载</button>
<div id="module-results"></div>
</div>
<div class="test-section">
<h2>2. 签名功能测试</h2>
<button onclick="testSignature()">测试签名生成和验证</button>
<div id="signature-results"></div>
</div>
<div class="test-section">
<h2>3. 请求配置测试</h2>
<button onclick="testRequestConfig()">测试请求配置</button>
<div id="config-results"></div>
</div>
<div class="test-section">
<h2>4. 错误处理测试</h2>
<button onclick="testErrorHandling()">测试错误处理</button>
<div id="error-results"></div>
</div>
<div class="test-section">
<h2>5. 小程序环境兼容性测试</h2>
<button onclick="testMiniappCompatibility()">测试小程序兼容性</button>
<div id="miniapp-results"></div>
</div>
<div class="test-section">
<h2>6. UniApp 环境兼容性测试</h2>
<button onclick="testUniappCompatibility()">测试UniApp兼容性</button>
<div id="uniapp-results"></div>
</div>
<div class="test-section">
<h2>7. 性能测试</h2>
<button onclick="testPerformance()">测试性能</button>
<div id="performance-results"></div>
</div>
<!-- 加载 UMD 格式的库 -->
<script src="../dist/index.umd.js"></script>
<script>
function logResult(containerId, message, type = 'info') {
const container = document.getElementById(containerId);
const div = document.createElement('div');
div.className = `result ${type}`;
div.innerHTML = message;
container.appendChild(div);
console.log(`[${type.toUpperCase()}] ${message}`);
}
function clearResults(containerId) {
document.getElementById(containerId).innerHTML = '';
}
// 1. 模块加载测试
function testModuleLoading() {
clearResults('module-results');
try {
// 测试全局对象
if (typeof window.GlskFetch === 'undefined') {
throw new Error('GlskFetch 全局对象不存在');
}
logResult('module-results', '✅ GlskFetch 全局对象存在', 'success');
// 测试解构赋值
const { Request, generateSignature, verifySignature } = window.GlskFetch;
logResult('module-results', '✅ 解构赋值成功', 'success');
// 测试类型
logResult('module-results', `Request 类型: ${typeof Request}`, 'info');
logResult('module-results', `generateSignature 类型: ${typeof generateSignature}`, 'info');
logResult('module-results', `verifySignature 类型: ${typeof verifySignature}`, 'info');
// 测试可用方法
const methods = Object.keys(window.GlskFetch);
logResult('module-results', `可用方法: ${methods.join(', ')}`, 'info');
} catch (error) {
logResult('module-results', `❌ 模块加载失败: ${error.message}`, 'error');
}
}
// 2. 签名功能测试
function testSignature() {
clearResults('signature-results');
try {
const { generateSignature, verifySignature } = window.GlskFetch;
// 基础签名测试
const basicOptions = {
appId: 'test-app-id',
appSecret: 'test-app-secret',
params: {
userId: 12345,
action: 'getData'
}
};
const signature1 = generateSignature(basicOptions);
logResult('signature-results', '✅ 基础签名生成成功', 'success');
logResult('signature-results', `签名: ${signature1.signature}`, 'info');
logResult('signature-results', `时间戳: ${signature1.timestamp}`, 'info');
logResult('signature-results', `随机数: ${signature1.nonce}`, 'info');
// 验证签名
const isValid1 = verifySignature({
...basicOptions,
signature: signature1.signature,
timestamp: signature1.timestamp,
nonce: signature1.nonce
});
logResult('signature-results', `✅ 签名验证结果: ${isValid1}`, isValid1 ? 'success' : 'error');
// 复杂参数签名测试
const complexOptions = {
appId: 'complex-test',
appSecret: 'complex-secret',
params: {
user: {
id: 67890,
name: 'testUser',
roles: ['admin', 'user']
},
data: {
nested: {
value: 'test',
array: [1, 2, 3]
}
},
timestamp: Date.now()
}
};
const signature2 = generateSignature(complexOptions);
logResult('signature-results', '✅ 复杂参数签名生成成功', 'success');
const isValid2 = verifySignature({
...complexOptions,
signature: signature2.signature,
timestamp: signature2.timestamp,
nonce: signature2.nonce
});
logResult('signature-results', `✅ 复杂参数签名验证结果: ${isValid2}`, isValid2 ? 'success' : 'error');
// 错误签名测试
const isInvalid = verifySignature({
...basicOptions,
signature: 'invalid-signature',
timestamp: signature1.timestamp,
nonce: signature1.nonce
});
logResult('signature-results', `✅ 错误签名验证结果: ${isInvalid} (应为false)`, !isInvalid ? 'success' : 'error');
} catch (error) {
logResult('signature-results', `❌ 签名功能测试失败: ${error.message}`, 'error');
}
}
// 3. 请求配置测试
function testRequestConfig() {
clearResults('config-results');
try {
const { Request } = window.GlskFetch;
// 基础配置测试
const basicRequest = new Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
logResult('config-results', '✅ 基础配置实例化成功', 'success');
// 完整配置测试
const fullRequest = new Request({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-token',
'User-Agent': 'glsk-fetch-test/1.0.0'
},
retries: 3,
retryDelay: 1000
});
logResult('config-results', '✅ 完整配置实例化成功', 'success');
// 测试实例方法
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(fullRequest));
logResult('config-results', `实例方法: ${methods.join(', ')}`, 'info');
// 测试配置继承
const childRequest = new Request({
baseURL: 'https://child.api.com'
});
logResult('config-results', '✅ 配置继承测试成功', 'success');
} catch (error) {
logResult('config-results', `❌ 请求配置测试失败: ${error.message}`, 'error');
}
}
// 4. 错误处理测试
function testErrorHandling() {
clearResults('error-results');
try {
const { Request, generateSignature } = window.GlskFetch;
// 测试无效配置
try {
new Request(null);
logResult('error-results', '❌ 应该抛出错误但没有', 'error');
} catch (error) {
logResult('error-results', '✅ 无效配置正确抛出错误', 'success');
}
// 测试签名错误处理
try {
generateSignature({});
logResult('error-results', '❌ 签名参数不完整应该抛出错误', 'error');
} catch (error) {
logResult('error-results', '✅ 签名参数验证正确', 'success');
}
// 测试超时处理
const timeoutRequest = new Request({
baseURL: 'https://api.example.com',
timeout: 1
});
logResult('error-results', '✅ 超时配置设置成功', 'success');
logResult('error-results', '✅ 错误处理测试完成', 'success');
} catch (error) {
logResult('error-results', `❌ 错误处理测试失败: ${error.message}`, 'error');
}
}
// 5. 小程序环境兼容性测试
function testMiniappCompatibility() {
clearResults('miniapp-results');
try {
// 模拟小程序环境
window.wx = {
request: function(options) {
console.log('模拟 wx.request:', options);
setTimeout(() => {
if (options.success) {
options.success({
data: { message: '小程序请求成功' },
statusCode: 200
});
}
}, 100);
},
getSystemInfo: function(options) {
if (options.success) {
options.success({
platform: 'miniapp',
system: 'iOS 14.0',
version: '8.0.0'
});
}
}
};
const { Request } = window.GlskFetch;
// 小程序环境请求测试
const miniappRequest = new Request({
baseURL: 'https://api.miniapp.com',
timeout: 8000,
headers: {
'Content-Type': 'application/json'
}
});
logResult('miniapp-results', '✅ 小程序环境 Request 创建成功', 'success');
logResult('miniapp-results', '✅ wx 对象模拟成功', 'success');
// 测试小程序特定配置
wx.getSystemInfo({
success: function(res) {
logResult('miniapp-results', `✅ 系统信息获取成功: ${res.platform}`, 'success');
}
});
logResult('miniapp-results', '✅ 小程序兼容性测试完成', 'success');
} catch (error) {
logResult('miniapp-results', `❌ 小程序兼容性测试失败: ${error.message}`, 'error');
}
}
// 6. UniApp 环境兼容性测试
function testUniappCompatibility() {
clearResults('uniapp-results');
try {
// 模拟 UniApp 环境
window.uni = {
request: function(options) {
console.log('模拟 uni.request:', options);
return new Promise((resolve) => {
setTimeout(() => {
resolve({
data: { message: 'UniApp 请求成功' },
statusCode: 200
});
}, 100);
});
},
getSystemInfo: function() {
return {
platform: 'uniapp',
system: 'Android 11',
uniPlatform: 'app-plus'
};
}
};
const { Request } = window.GlskFetch;
// UniApp 环境请求测试
const uniappRequest = new Request({
baseURL: 'https://api.uniapp.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'UniApp/1.0.0'
}
});
logResult('uniapp-results', '✅ UniApp 环境 Request 创建成功', 'success');
logResult('uniapp-results', '✅ uni 对象模拟成功', 'success');
// 测试 UniApp 特定功能
const systemInfo = uni.getSystemInfo();
logResult('uniapp-results', `✅ 系统信息: ${systemInfo.platform} - ${systemInfo.system}`, 'success');
// 测试异步请求
uni.request({
url: 'https://api.uniapp.com/test',
method: 'GET'
}).then(response => {
logResult('uniapp-results', '✅ UniApp 异步请求测试成功', 'success');
});
logResult('uniapp-results', '✅ UniApp 兼容性测试完成', 'success');
} catch (error) {
logResult('uniapp-results', `❌ UniApp 兼容性测试失败: ${error.message}`, 'error');
}
}
// 7. 性能测试
function testPerformance() {
clearResults('performance-results');
try {
const { Request, generateSignature } = window.GlskFetch;
// 实例化性能测试
const startTime1 = performance.now();
for (let i = 0; i < 1000; i++) {
new Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
}
const endTime1 = performance.now();
logResult('performance-results', `✅ 1000次实例化耗时: ${(endTime1 - startTime1).toFixed(2)}ms`, 'success');
// 签名生成性能测试
const signatureOptions = {
appId: 'perf-test',
appSecret: 'perf-secret',
params: {
data: 'performance test data',
timestamp: Date.now()
}
};
const startTime2 = performance.now();
for (let i = 0; i < 1000; i++) {
generateSignature(signatureOptions);
}
const endTime2 = performance.now();
logResult('performance-results', `✅ 1000次签名生成耗时: ${(endTime2 - startTime2).toFixed(2)}ms`, 'success');
// 内存使用测试
const memoryBefore = performance.memory ? performance.memory.usedJSHeapSize : 0;
const requests = [];
for (let i = 0; i < 100; i++) {
requests.push(new Request({
baseURL: `https://api${i}.example.com`,
timeout: 5000
}));
}
const memoryAfter = performance.memory ? performance.memory.usedJSHeapSize : 0;
if (performance.memory) {
const memoryUsed = ((memoryAfter - memoryBefore) / 1024).toFixed(2);
logResult('performance-results', `✅ 100个实例内存使用: ${memoryUsed}KB`, 'success');
} else {
logResult('performance-results', '⚠️ 浏览器不支持内存监控', 'info');
}
logResult('performance-results', '✅ 性能测试完成', 'success');
} catch (error) {
logResult('performance-results', `❌ 性能测试失败: ${error.message}`, 'error');
}
}
// 页面加载完成后自动运行基础测试
window.addEventListener('load', function() {
console.log('=== glsk-fetch 核心功能综合测试页面加载完成 ===');
testModuleLoading();
});
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
// Defaults 类使用示例
const Request = require('../dist/index').default;
const { Defaults } = require('../dist/index');
// 创建全局默认配置
const globalDefaults = new Defaults({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Authorization': 'Bearer global-token',
'X-App-Version': '1.0.0'
},
appId: 'global-app-id',
appSecret: 'global-app-secret',
retries: 2,
retryDelay: 500
});
console.log('全局默认配置:', globalDefaults);
// 创建使用全局配置的请求实例
const request1 = new Request(globalDefaults);
// 创建使用自定义配置的请求实例
const request2 = new Request({
baseURL: 'https://api.another-service.com',
timeout: 5000,
headers: {
'Authorization': 'Bearer service-token'
}
});
// 模拟请求
console.log('\n请求实例1配置:');
console.log('- baseURL:', request1.defaults.baseURL);
console.log('- timeout:', request1.defaults.timeout);
console.log('- Authorization:', request1.defaults.headers['Authorization']);
console.log('\n请求实例2配置:');
console.log('- baseURL:', request2.defaults.baseURL);
console.log('- timeout:', request2.defaults.timeout);
console.log('- Authorization:', request2.defaults.headers['Authorization']);
// 演示如何使用 merge 方法创建特定请求的配置
console.log('\n使用 merge 方法创建特定请求配置:');
const specificConfig = request1.defaults.merge({
timeout: 3000,
headers: {
'X-Request-ID': 'specific-request-123'
},
params: {
lang: 'zh-CN'
}
});
console.log('合并后的特定请求配置:');
console.log('- baseURL:', specificConfig.baseURL); // 保留原值
console.log('- timeout:', specificConfig.timeout); // 更新为新值
console.log('- Authorization:', specificConfig.headers['Authorization']); // 保留原值
console.log('- X-Request-ID:', specificConfig.headers['X-Request-ID']); // 新增值
console.log('- params:', specificConfig.params); // 新增值
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Data Test</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;
gap: 20px;
}
.panel {
flex: 1;
border: 1px solid #ccc;
border-radius: 5px;
padding: 15px;
}
button {
margin: 10px 0;
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
pre {
background-color: #f5f5f5;
padding: 10px;
border-radius: 5px;
overflow: auto;
max-height: 300px;
}
</style>
</head>
<body>
<h1>POST请求参数测试</h1>
<div class="container">
<div class="panel">
<h2>JSON格式</h2>
<p>默认使用JSON格式发送POST请求</p>
<button id="testJsonBtn">测试JSON格式</button>
<pre id="jsonResult">结果将显示在这里...</pre>
</div>
<div class="panel">
<h2>表单格式</h2>
<p>使用application/x-www-form-urlencoded格式发送POST请求</p>
<button id="testFormBtn">测试表单格式</button>
<pre id="formResult">结果将显示在这里...</pre>
</div>
</div>
<script>
// 初始化请求库
const GlskFetch = window.GlskFetch.default;
// 创建请求实例,提供必要的初始化参数
const fetch = new GlskFetch({
sentryDsn: 'https://example@sentry.io/123456', // 提供一个示例Sentry DSN
disableSentry: true // 禁用Sentry,避免实际发送错误报告
});
// 测试数据
const testData = {
name: '测试用户',
age: 30,
items: ['item1', 'item2']
};
// 测试JSON格式
document.getElementById('testJsonBtn').addEventListener('click', async () => {
try {
const response = await fetch.post('https://httpbin.org/post', testData);
document.getElementById('jsonResult').textContent = JSON.stringify(response.data, null, 2);
console.log('JSON格式响应:', response);
} catch (error) {
document.getElementById('jsonResult').textContent = '错误: ' + error.message;
console.error('JSON格式错误:', error);
}
});
// 测试表单格式
document.getElementById('testFormBtn').addEventListener('click', async () => {
try {
const response = await fetch.post('https://httpbin.org/post', testData, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
document.getElementById('formResult').textContent = JSON.stringify(response.data, null, 2);
console.log('表单格式响应:', response);
} catch (error) {
document.getElementById('formResult').textContent = '错误: ' + error.message;
console.error('表单格式错误:', error);
}
});
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
// 小程序环境 - CJS 格式兼容性测试
// 使用 CommonJS 格式导入
const { Request, generateSignature, verifySignature } = require('../dist/index.js');
console.log('=== 小程序 CJS 格式兼容性测试 ===');
// 测试模块导入
console.log('1. 模块导入测试:');
console.log('Request 类:', typeof Request);
console.log('generateSignature 函数:', typeof generateSignature);
console.log('verifySignature 函数:', typeof verifySignature);
// 测试基本实例化
console.log('\n2. 实例化测试:');
try {
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
console.log('✅ Request 实例化成功');
console.log('实例类型:', typeof request);
console.log('实例方法:', Object.getOwnPropertyNames(Object.getPrototypeOf(request)));
} catch (error) {
console.error('❌ Request 实例化失败:', error.message);
}
// 测试签名功能
console.log('\n3. 签名功能测试:');
try {
const signatureOptions = {
appId: 'test-app-id',
appSecret: 'test-app-secret',
params: {
name: 'test',
value: 123
}
};
const signature = generateSignature(signatureOptions);
console.log('✅ 签名生成成功');
console.log('签名结果:', signature);
// 验证签名
const isValid = verifySignature({
...signatureOptions,
signature: signature.signature,
timestamp: signature.timestamp,
nonce: signature.nonce
});
console.log('✅ 签名验证结果:', isValid);
} catch (error) {
console.error('❌ 签名功能测试失败:', error.message);
}
// 测试请求配置
console.log('\n4. 请求配置测试:');
try {
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
},
// 小程序环境特定配置
adapter: 'miniapp'
});
// 测试请求配置
const config = {
url: '/test',
method: 'POST',
data: {
test: 'data'
}
};
console.log('✅ 请求配置创建成功');
console.log('配置对象:', config);
} catch (error) {
console.error('❌ 请求配置测试失败:', error.message);
}
// 测试错误处理
console.log('\n5. 错误处理测试:');
try {
// 测试无效参数
const request = new Request();
console.log('✅ 默认配置实例化成功');
} catch (error) {
console.log('错误处理:', error.message);
}
console.log('\n=== CJS 格式兼容性测试完成 ===');
// 导出测试结果供小程序页面使用
module.exports = {
testResult: 'CJS format compatibility test completed',
timestamp: new Date().toISOString()
};
\ No newline at end of file \ No newline at end of file
// 小程序环境下使用 Sentry 的示例
const { Request } = require('../dist');
// 创建请求实例,并配置 Sentry
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置 - 在小程序环境中会自动使用 sentry-miniapp.js
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'miniprogram',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起请求
function fetchData() {
return request.request({
url: '/api/data',
method: 'GET'
}).then(response => {
console.log('请求成功:', response);
return response;
}).catch(error => {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
throw error;
});
}
// 在小程序页面中使用
Page({
data: {
result: null,
loading: false,
error: null
},
onLoad: function() {
this.loadData();
},
loadData: function() {
this.setData({ loading: true, error: null });
fetchData()
.then(response => {
this.setData({
result: response.data,
loading: false
});
})
.catch(error => {
this.setData({
error: error.message,
loading: false
});
});
}
});
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小程序 UMD 格式兼容性测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.test-section {
background: white;
margin: 10px 0;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.success { color: #28a745; }
.error { color: #dc3545; }
.info { color: #17a2b8; }
pre {
background: #f8f9fa;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}
button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:hover {
background: #0056b3;
}
</style>
</head>
<body>
<h1>小程序 UMD 格式兼容性测试</h1>
<div class="test-section">
<h2>测试控制</h2>
<button onclick="runAllTests()">运行所有测试</button>
<button onclick="clearResults()">清空结果</button>
</div>
<div class="test-section">
<h2>1. 模块加载测试</h2>
<div id="module-test-result"></div>
</div>
<div class="test-section">
<h2>2. 实例化测试</h2>
<div id="instance-test-result"></div>
</div>
<div class="test-section">
<h2>3. 签名功能测试</h2>
<div id="signature-test-result"></div>
</div>
<div class="test-section">
<h2>4. 请求配置测试</h2>
<div id="config-test-result"></div>
</div>
<div class="test-section">
<h2>5. 小程序环境模拟测试</h2>
<div id="miniapp-test-result"></div>
</div>
<!-- 加载 UMD 格式的库 -->
<script src="../dist/index.umd.js"></script>
<script>
console.log('=== 小程序 UMD 格式兼容性测试 ===');
function log(elementId, message, type = 'info') {
const element = document.getElementById(elementId);
const className = type === 'success' ? 'success' : type === 'error' ? 'error' : 'info';
element.innerHTML += `<div class="${className}">${message}</div>`;
console.log(message);
}
function clearResults() {
const resultElements = document.querySelectorAll('[id$="-test-result"]');
resultElements.forEach(el => el.innerHTML = '');
}
// 1. 模块加载测试
function testModuleLoading() {
const elementId = 'module-test-result';
log(elementId, '开始模块加载测试...');
try {
// 检查全局对象
if (typeof GlskFetch !== 'undefined') {
log(elementId, '✅ GlskFetch 全局对象存在', 'success');
log(elementId, `GlskFetch 类型: ${typeof GlskFetch}`);
// 检查导出的成员
const exports = Object.keys(GlskFetch);
log(elementId, `导出成员: ${exports.join(', ')}`);
if (GlskFetch.Request) {
log(elementId, '✅ Request 类存在', 'success');
}
if (GlskFetch.generateSignature) {
log(elementId, '✅ generateSignature 函数存在', 'success');
}
if (GlskFetch.verifySignature) {
log(elementId, '✅ verifySignature 函数存在', 'success');
}
} else {
log(elementId, '❌ GlskFetch 全局对象不存在', 'error');
}
} catch (error) {
log(elementId, `❌ 模块加载测试失败: ${error.message}`, 'error');
}
}
// 2. 实例化测试
function testInstantiation() {
const elementId = 'instance-test-result';
log(elementId, '开始实例化测试...');
try {
if (GlskFetch && GlskFetch.Request) {
const request = new GlskFetch.Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
log(elementId, '✅ Request 实例化成功', 'success');
log(elementId, `实例类型: ${typeof request}`);
// 检查实例方法
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(request));
log(elementId, `实例方法: ${methods.join(', ')}`);
// 检查关键方法
if (typeof request.request === 'function') {
log(elementId, '✅ request 方法存在', 'success');
}
if (typeof request.get === 'function') {
log(elementId, '✅ get 方法存在', 'success');
}
if (typeof request.post === 'function') {
log(elementId, '✅ post 方法存在', 'success');
}
} else {
log(elementId, '❌ Request 类不可用', 'error');
}
} catch (error) {
log(elementId, `❌ 实例化测试失败: ${error.message}`, 'error');
}
}
// 3. 签名功能测试
function testSignature() {
const elementId = 'signature-test-result';
log(elementId, '开始签名功能测试...');
try {
if (GlskFetch && GlskFetch.generateSignature && GlskFetch.verifySignature) {
const signatureOptions = {
appId: 'test-app-id',
appSecret: 'test-app-secret',
params: {
name: 'test',
value: 123
}
};
const signature = GlskFetch.generateSignature(signatureOptions);
log(elementId, '✅ 签名生成成功', 'success');
log(elementId, `签名结果: ${JSON.stringify(signature, null, 2)}`);
// 验证签名
const isValid = GlskFetch.verifySignature({
...signatureOptions,
signature: signature.signature,
timestamp: signature.timestamp,
nonce: signature.nonce
});
if (isValid) {
log(elementId, '✅ 签名验证成功', 'success');
} else {
log(elementId, '❌ 签名验证失败', 'error');
}
} else {
log(elementId, '❌ 签名函数不可用', 'error');
}
} catch (error) {
log(elementId, `❌ 签名功能测试失败: ${error.message}`, 'error');
}
}
// 4. 请求配置测试
function testRequestConfig() {
const elementId = 'config-test-result';
log(elementId, '开始请求配置测试...');
try {
if (GlskFetch && GlskFetch.Request) {
const request = new GlskFetch.Request({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
});
log(elementId, '✅ 请求实例创建成功', 'success');
// 测试配置合并
const config = {
url: '/test',
method: 'POST',
data: {
test: 'data'
}
};
log(elementId, '✅ 请求配置创建成功', 'success');
log(elementId, `配置对象: ${JSON.stringify(config, null, 2)}`);
} else {
log(elementId, '❌ Request 类不可用', 'error');
}
} catch (error) {
log(elementId, `❌ 请求配置测试失败: ${error.message}`, 'error');
}
}
// 5. 小程序环境模拟测试
function testMiniappEnvironment() {
const elementId = 'miniapp-test-result';
log(elementId, '开始小程序环境模拟测试...');
try {
// 模拟小程序全局对象
if (typeof wx === 'undefined') {
window.wx = {
request: function(options) {
log(elementId, '模拟 wx.request 调用', 'info');
log(elementId, `请求参数: ${JSON.stringify(options, null, 2)}`);
// 模拟成功响应
setTimeout(() => {
if (options.success) {
options.success({
data: { message: '模拟响应数据' },
statusCode: 200
});
}
}, 100);
}
};
log(elementId, '✅ 小程序环境模拟成功', 'success');
}
// 测试在模拟环境下的请求
if (GlskFetch && GlskFetch.Request) {
const request = new GlskFetch.Request({
baseURL: 'https://api.example.com'
});
log(elementId, '✅ 小程序环境下实例化成功', 'success');
}
} catch (error) {
log(elementId, `❌ 小程序环境测试失败: ${error.message}`, 'error');
}
}
// 运行所有测试
function runAllTests() {
clearResults();
console.log('开始运行所有测试...');
testModuleLoading();
testInstantiation();
testSignature();
testRequestConfig();
testMiniappEnvironment();
console.log('所有测试完成');
}
// 页面加载完成后自动运行测试
window.addEventListener('load', function() {
setTimeout(runAllTests, 500);
});
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
import { Request } from '../src';
// 创建请求实例,必须提供 sentryDsn
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置(必填)
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'development',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起请求
const fetchData = async () => {
try {
const response = await request.request({
url: '/api/data',
method: 'GET'
});
console.log('请求成功:', response);
} catch (error) {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
}
};
// 执行示例
(async () => {
console.log('开始测试必填 sentryDsn 功能...');
try {
await fetchData();
console.log('测试完成');
} catch (error) {
console.error('测试失败:', error);
}
// 尝试创建没有 sentryDsn 的实例(会抛出错误)
try {
// @ts-ignore - 故意忽略类型检查以演示运行时错误
const invalidRequest = new Request({
baseURL: 'https://api.example.com'
// 缺少必填的 sentryDsn
});
console.log('这行代码不应该被执行');
} catch (error) {
console.log('预期的错误:', error.message);
}
})();
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sentry 兼容性测试</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.test-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
.success { color: green; }
.error { color: red; }
.info { color: blue; }
.warning { color: orange; }
button { padding: 10px 15px; margin: 5px; cursor: pointer; }
pre { background: #f5f5f5; padding: 10px; border-radius: 3px; overflow-x: auto; }
.result { margin: 10px 0; padding: 10px; background: #f9f9f9; border-radius: 3px; }
.sentry-event { background: #fff3cd; border: 1px solid #ffeaa7; padding: 10px; margin: 5px 0; border-radius: 3px; }
</style>
</head>
<body>
<h1>Sentry 错误上报兼容性测试</h1>
<div class="test-section">
<h2>1. Sentry 初始化测试</h2>
<button onclick="testSentryInit()">测试 Sentry 初始化</button>
<div id="sentry-init-results"></div>
</div>
<div class="test-section">
<h2>2. 小程序环境 Sentry 测试</h2>
<button onclick="testMiniappSentry()">测试小程序 Sentry</button>
<div id="miniapp-sentry-results"></div>
</div>
<div class="test-section">
<h2>3. UniApp 环境 Sentry 测试</h2>
<button onclick="testUniappSentry()">测试 UniApp Sentry</button>
<div id="uniapp-sentry-results"></div>
</div>
<div class="test-section">
<h2>4. 错误捕获和上报测试</h2>
<button onclick="testErrorCapture()">测试错误捕获</button>
<div id="error-capture-results"></div>
</div>
<div class="test-section">
<h2>5. 性能监控测试</h2>
<button onclick="testPerformanceMonitoring()">测试性能监控</button>
<div id="performance-monitoring-results"></div>
</div>
<div class="test-section">
<h2>6. 自定义事件测试</h2>
<button onclick="testCustomEvents()">测试自定义事件</button>
<div id="custom-events-results"></div>
</div>
<!-- 加载 UMD 格式的库 -->
<script src="../dist/index.umd.js"></script>
<script>
// 模拟 Sentry SDK
window.Sentry = {
init: function(options) {
console.log('Sentry.init called with:', options);
this._options = options;
this._isInitialized = true;
this._events = [];
return this;
},
captureException: function(error, context) {
console.log('Sentry.captureException:', error, context);
const event = {
type: 'exception',
error: error,
context: context,
timestamp: Date.now(),
environment: this._options?.environment || 'unknown'
};
this._events.push(event);
return event;
},
captureMessage: function(message, level, context) {
console.log('Sentry.captureMessage:', message, level, context);
const event = {
type: 'message',
message: message,
level: level || 'info',
context: context,
timestamp: Date.now(),
environment: this._options?.environment || 'unknown'
};
this._events.push(event);
return event;
},
addBreadcrumb: function(breadcrumb) {
console.log('Sentry.addBreadcrumb:', breadcrumb);
if (!this._breadcrumbs) this._breadcrumbs = [];
this._breadcrumbs.push({
...breadcrumb,
timestamp: Date.now()
});
},
setContext: function(key, context) {
console.log('Sentry.setContext:', key, context);
if (!this._contexts) this._contexts = {};
this._contexts[key] = context;
},
setTag: function(key, value) {
console.log('Sentry.setTag:', key, value);
if (!this._tags) this._tags = {};
this._tags[key] = value;
},
setUser: function(user) {
console.log('Sentry.setUser:', user);
this._user = user;
},
startTransaction: function(context) {
console.log('Sentry.startTransaction:', context);
return {
name: context.name,
op: context.op,
startTime: Date.now(),
finish: function() {
this.endTime = Date.now();
console.log('Transaction finished:', this);
},
setTag: function(key, value) {
if (!this.tags) this.tags = {};
this.tags[key] = value;
}
};
},
// 获取捕获的事件(测试用)
getEvents: function() {
return this._events || [];
},
getBreadcrumbs: function() {
return this._breadcrumbs || [];
},
getContexts: function() {
return this._contexts || {};
},
getTags: function() {
return this._tags || {};
},
isInitialized: function() {
return this._isInitialized || false;
}
};
function logResult(containerId, message, type = 'info') {
const container = document.getElementById(containerId);
const div = document.createElement('div');
div.className = `result ${type}`;
div.innerHTML = message;
container.appendChild(div);
console.log(`[${type.toUpperCase()}] ${message}`);
}
function clearResults(containerId) {
document.getElementById(containerId).innerHTML = '';
}
function showSentryEvent(containerId, event) {
const container = document.getElementById(containerId);
const div = document.createElement('div');
div.className = 'sentry-event';
div.innerHTML = `
<strong>Sentry Event:</strong><br>
Type: ${event.type}<br>
${event.error ? `Error: ${event.error.message}<br>` : ''}
${event.message ? `Message: ${event.message}<br>` : ''}
Environment: ${event.environment}<br>
Timestamp: ${new Date(event.timestamp).toLocaleString()}
`;
container.appendChild(div);
}
// 1. Sentry 初始化测试
function testSentryInit() {
clearResults('sentry-init-results');
try {
// 基础初始化
Sentry.init({
dsn: 'https://test@sentry.io/test',
environment: 'test',
debug: true
});
logResult('sentry-init-results', '✅ Sentry 基础初始化成功', 'success');
logResult('sentry-init-results', `初始化状态: ${Sentry.isInitialized()}`, 'info');
// 小程序环境初始化
Sentry.init({
dsn: 'https://miniapp@sentry.io/miniapp',
environment: 'miniapp',
integrations: [],
beforeSend: function(event) {
console.log('小程序 beforeSend:', event);
return event;
}
});
logResult('sentry-init-results', '✅ 小程序环境 Sentry 初始化成功', 'success');
// UniApp 环境初始化
Sentry.init({
dsn: 'https://uniapp@sentry.io/uniapp',
environment: 'uniapp',
tracesSampleRate: 1.0,
beforeSend: function(event) {
console.log('UniApp beforeSend:', event);
return event;
}
});
logResult('sentry-init-results', '✅ UniApp 环境 Sentry 初始化成功', 'success');
} catch (error) {
logResult('sentry-init-results', `❌ Sentry 初始化失败: ${error.message}`, 'error');
}
}
// 2. 小程序环境 Sentry 测试
function testMiniappSentry() {
clearResults('miniapp-sentry-results');
try {
// 模拟小程序环境
window.wx = {
request: function(options) {
console.log('wx.request for Sentry:', options);
// 模拟网络错误
setTimeout(() => {
if (options.fail) {
options.fail({
errMsg: '模拟网络错误',
statusCode: 500
});
}
}, 100);
},
getSystemInfo: function(options) {
if (options.success) {
options.success({
platform: 'miniapp',
system: 'iOS 14.0',
version: '8.0.0',
SDKVersion: '2.19.0'
});
}
}
};
const { Request } = window.GlskFetch;
// 初始化小程序 Sentry
Sentry.init({
dsn: 'https://miniapp@sentry.io/miniapp',
environment: 'miniapp'
});
// 设置小程序上下文
Sentry.setContext('miniapp', {
platform: 'miniapp',
version: '1.0.0'
});
Sentry.setTag('platform', 'miniapp');
Sentry.setUser({
id: 'miniapp-user-123',
platform: 'miniapp'
});
logResult('miniapp-sentry-results', '✅ 小程序 Sentry 上下文设置成功', 'success');
// 创建小程序请求实例
const miniappRequest = new Request({
baseURL: 'https://api.miniapp.com',
timeout: 5000
});
// 模拟小程序错误
try {
throw new Error('小程序测试错误');
} catch (error) {
const event = Sentry.captureException(error, {
tags: { source: 'miniapp-test' },
extra: { requestInstance: 'miniapp' }
});
showSentryEvent('miniapp-sentry-results', event);
}
// 添加面包屑
Sentry.addBreadcrumb({
message: '小程序页面加载',
category: 'navigation',
level: 'info'
});
Sentry.addBreadcrumb({
message: '小程序请求发送',
category: 'http',
level: 'info',
data: {
url: 'https://api.miniapp.com/test',
method: 'GET'
}
});
logResult('miniapp-sentry-results', '✅ 小程序面包屑添加成功', 'success');
logResult('miniapp-sentry-results', `面包屑数量: ${Sentry.getBreadcrumbs().length}`, 'info');
// 测试小程序特定错误
wx.request({
url: 'https://api.miniapp.com/error',
method: 'GET',
success: function(res) {
console.log('小程序请求成功:', res);
},
fail: function(err) {
const event = Sentry.captureException(new Error(`小程序请求失败: ${err.errMsg}`), {
tags: { source: 'wx.request' },
extra: { error: err }
});
showSentryEvent('miniapp-sentry-results', event);
}
});
logResult('miniapp-sentry-results', '✅ 小程序 Sentry 测试完成', 'success');
} catch (error) {
logResult('miniapp-sentry-results', `❌ 小程序 Sentry 测试失败: ${error.message}`, 'error');
}
}
// 3. UniApp 环境 Sentry 测试
function testUniappSentry() {
clearResults('uniapp-sentry-results');
try {
// 模拟 UniApp 环境
window.uni = {
request: function(options) {
console.log('uni.request for Sentry:', options);
return new Promise((resolve, reject) => {
setTimeout(() => {
// 模拟随机错误
if (Math.random() > 0.7) {
reject({
errMsg: '模拟 UniApp 网络错误',
statusCode: 500
});
} else {
resolve({
data: { message: 'UniApp 请求成功' },
statusCode: 200
});
}
}, 200);
});
},
getSystemInfo: function() {
return {
platform: 'uniapp',
system: 'Android 11',
uniPlatform: 'app-plus',
uniVersion: '3.0.0'
};
}
};
const { Request } = window.GlskFetch;
// 初始化 UniApp Sentry
Sentry.init({
dsn: 'https://uniapp@sentry.io/uniapp',
environment: 'uniapp',
tracesSampleRate: 1.0
});
// 设置 UniApp 上下文
const systemInfo = uni.getSystemInfo();
Sentry.setContext('uniapp', systemInfo);
Sentry.setTag('platform', 'uniapp');
Sentry.setTag('uniPlatform', systemInfo.uniPlatform);
Sentry.setUser({
id: 'uniapp-user-456',
platform: 'uniapp'
});
logResult('uniapp-sentry-results', '✅ UniApp Sentry 上下文设置成功', 'success');
// 创建 UniApp 请求实例
const uniappRequest = new Request({
baseURL: 'https://api.uniapp.com',
timeout: 8000
});
// 开始性能监控
const transaction = Sentry.startTransaction({
name: 'UniApp 页面加载',
op: 'navigation'
});
transaction.setTag('page', 'test-page');
// 模拟 UniApp 异步操作
async function testUniappAsync() {
try {
Sentry.addBreadcrumb({
message: 'UniApp 异步操作开始',
category: 'async',
level: 'info'
});
const response = await uni.request({
url: 'https://api.uniapp.com/test',
method: 'POST',
data: { test: 'data' }
});
logResult('uniapp-sentry-results', '✅ UniApp 异步请求成功', 'success');
Sentry.addBreadcrumb({
message: 'UniApp 异步操作成功',
category: 'async',
level: 'info',
data: response
});
} catch (error) {
const event = Sentry.captureException(new Error(`UniApp 异步操作失败: ${error.errMsg}`), {
tags: { source: 'uni.request', async: true },
extra: { error: error }
});
showSentryEvent('uniapp-sentry-results', event);
} finally {
transaction.finish();
logResult('uniapp-sentry-results', '✅ UniApp 性能监控完成', 'success');
}
}
// 运行异步测试
testUniappAsync();
// 测试 UniApp 特定错误
try {
throw new Error('UniApp 测试错误');
} catch (error) {
const event = Sentry.captureException(error, {
tags: { source: 'uniapp-test' },
extra: {
systemInfo: systemInfo,
requestInstance: 'uniapp'
}
});
showSentryEvent('uniapp-sentry-results', event);
}
logResult('uniapp-sentry-results', '✅ UniApp Sentry 测试完成', 'success');
} catch (error) {
logResult('uniapp-sentry-results', `❌ UniApp Sentry 测试失败: ${error.message}`, 'error');
}
}
// 4. 错误捕获和上报测试
function testErrorCapture() {
clearResults('error-capture-results');
try {
const { Request, generateSignature } = window.GlskFetch;
// 测试不同类型的错误
// 1. JavaScript 错误
try {
undefined.someMethod();
} catch (error) {
const event = Sentry.captureException(error, {
tags: { errorType: 'javascript' }
});
showSentryEvent('error-capture-results', event);
}
// 2. 请求配置错误
try {
new Request(null);
} catch (error) {
const event = Sentry.captureException(error, {
tags: { errorType: 'request-config' }
});
showSentryEvent('error-capture-results', event);
}
// 3. 签名错误
try {
generateSignature({});
} catch (error) {
const event = Sentry.captureException(error, {
tags: { errorType: 'signature' }
});
showSentryEvent('error-capture-results', event);
}
// 4. 自定义错误消息
Sentry.captureMessage('这是一个测试消息', 'info', {
tags: { messageType: 'test' }
});
Sentry.captureMessage('这是一个警告消息', 'warning', {
tags: { messageType: 'warning' }
});
logResult('error-capture-results', '✅ 错误捕获测试完成', 'success');
logResult('error-capture-results', `捕获事件数量: ${Sentry.getEvents().length}`, 'info');
} catch (error) {
logResult('error-capture-results', `❌ 错误捕获测试失败: ${error.message}`, 'error');
}
}
// 5. 性能监控测试
function testPerformanceMonitoring() {
clearResults('performance-monitoring-results');
try {
const { Request, generateSignature } = window.GlskFetch;
// 测试请求性能监控
const requestTransaction = Sentry.startTransaction({
name: 'Request 实例化性能',
op: 'request.create'
});
const startTime = performance.now();
for (let i = 0; i < 100; i++) {
new Request({
baseURL: `https://api${i}.example.com`,
timeout: 5000
});
}
const endTime = performance.now();
const duration = endTime - startTime;
requestTransaction.setTag('count', '100');
requestTransaction.setTag('duration', duration.toFixed(2));
requestTransaction.finish();
logResult('performance-monitoring-results', `✅ 请求实例化性能监控完成: ${duration.toFixed(2)}ms`, 'success');
// 测试签名性能监控
const signatureTransaction = Sentry.startTransaction({
name: '签名生成性能',
op: 'signature.generate'
});
const signatureStartTime = performance.now();
for (let i = 0; i < 100; i++) {
generateSignature({
appId: `test-${i}`,
appSecret: 'test-secret',
params: { data: `test-data-${i}` }
});
}
const signatureEndTime = performance.now();
const signatureDuration = signatureEndTime - signatureStartTime;
signatureTransaction.setTag('count', '100');
signatureTransaction.setTag('duration', signatureDuration.toFixed(2));
signatureTransaction.finish();
logResult('performance-monitoring-results', `✅ 签名生成性能监控完成: ${signatureDuration.toFixed(2)}ms`, 'success');
// 添加性能相关面包屑
Sentry.addBreadcrumb({
message: '性能监控测试完成',
category: 'performance',
level: 'info',
data: {
requestDuration: duration,
signatureDuration: signatureDuration
}
});
logResult('performance-monitoring-results', '✅ 性能监控测试完成', 'success');
} catch (error) {
logResult('performance-monitoring-results', `❌ 性能监控测试失败: ${error.message}`, 'error');
}
}
// 6. 自定义事件测试
function testCustomEvents() {
clearResults('custom-events-results');
try {
const { Request } = window.GlskFetch;
// 自定义业务事件
Sentry.captureMessage('用户登录', 'info', {
tags: {
event: 'user_login',
platform: 'web'
},
extra: {
userId: 'test-user-123',
timestamp: Date.now()
}
});
Sentry.captureMessage('API 调用', 'info', {
tags: {
event: 'api_call',
endpoint: '/api/test'
},
extra: {
method: 'POST',
duration: 150
}
});
// 业务逻辑错误
Sentry.captureMessage('业务逻辑错误', 'error', {
tags: {
event: 'business_error',
errorCode: 'BIZ_001'
},
extra: {
description: '用户权限不足',
action: 'access_denied'
}
});
// 添加业务相关面包屑
Sentry.addBreadcrumb({
message: '用户点击按钮',
category: 'ui',
level: 'info',
data: {
buttonId: 'test-button',
page: 'sentry-test'
}
});
Sentry.addBreadcrumb({
message: '数据加载完成',
category: 'data',
level: 'info',
data: {
dataType: 'test-data',
count: 100
}
});
logResult('custom-events-results', '✅ 自定义事件测试完成', 'success');
logResult('custom-events-results', `总事件数量: ${Sentry.getEvents().length}`, 'info');
logResult('custom-events-results', `面包屑数量: ${Sentry.getBreadcrumbs().length}`, 'info');
logResult('custom-events-results', `上下文数量: ${Object.keys(Sentry.getContexts()).length}`, 'info');
logResult('custom-events-results', `标签数量: ${Object.keys(Sentry.getTags()).length}`, 'info');
} catch (error) {
logResult('custom-events-results', `❌ 自定义事件测试失败: ${error.message}`, 'error');
}
}
// 页面加载完成后自动初始化
window.addEventListener('load', function() {
console.log('=== Sentry 兼容性测试页面加载完成 ===');
testSentryInit();
});
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
const { Request, Sentry } = require('../dist');
// 创建请求实例,并提供 Sentry DSN
const request = new Request({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000,
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0', // 替换为实际的 Sentry DSN
sentryOptions: {
environment: 'development',
release: '1.0.0',
debug: true
}
});
// 发起一个正常请求
request.get('/posts/1')
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
});
// 发起一个会失败的请求(用于演示错误上报)
request.get('/non-existent-endpoint')
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
// 错误已自动上报到 Sentry
});
// 手动上报错误示例
setTimeout(() => {
try {
// 模拟一个业务逻辑错误
throw new Error('业务逻辑处理失败');
} catch (error) {
// 手动上报错误到 Sentry
Sentry.reportBusinessError(error.message, {
userId: '12345',
action: 'processData',
timestamp: new Date().toISOString()
});
console.error('业务错误已上报到 Sentry');
}
}, 1000);
// 参数验证错误示例
function validateUserData(userData) {
if (!userData.name) {
Sentry.reportValidationError('用户名不能为空', userData);
return false;
}
return true;
}
// 测试参数验证
const userData = { id: 1, email: 'test@example.com' }; // 缺少 name 字段
if (!validateUserData(userData)) {
console.error('用户数据验证失败,错误已上报到 Sentry');
}
\ No newline at end of file \ No newline at end of file
import { Request, initSentry, reportBusinessError, reportNetworkError, reportValidationError } from '../src';
// 创建请求实例,并配置 Sentry
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'development',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起正常请求
const fetchData = async () => {
try {
const response = await request.request({
url: '/api/data',
method: 'GET'
});
console.log('请求成功:', response);
} catch (error) {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
}
};
// 发起一个会失败的请求(用于测试错误上报)
const fetchInvalidData = async () => {
try {
const response = await request.request({
url: '/api/invalid',
method: 'GET',
timeout: 3000 // 3秒超时
});
console.log('请求成功:', response);
} catch (error) {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
}
};
// 手动上报业务错误
const reportCustomBusinessError = () => {
const businessData = {
userId: 12345,
action: 'checkout',
cartItems: [
{ id: 1, name: 'Product 1', price: 99.99 },
{ id: 2, name: 'Product 2', price: 149.99 }
],
totalAmount: 249.98
};
reportBusinessError('结算流程异常', businessData);
};
// 手动上报参数验证错误
const reportCustomValidationError = () => {
const invalidParams = {
email: 'invalid-email',
password: '123', // 密码太短
age: -5 // 年龄不能为负数
};
reportValidationError('用户注册参数验证失败', invalidParams);
};
// 手动上报网络错误
const reportCustomNetworkError = () => {
const requestInfo = {
url: 'https://api.example.com/data',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: { key: 'value' },
timestamp: new Date().toISOString()
};
reportNetworkError('API 服务不可用', requestInfo);
};
// 执行示例
(async () => {
console.log('开始测试 Sentry 功能...');
// 测试自动错误上报
await fetchData().catch(console.error);
await fetchInvalidData().catch(console.error);
// 测试手动错误上报
reportCustomBusinessError();
reportCustomValidationError();
reportCustomNetworkError();
console.log('测试完成,请检查 Sentry 控制台查看上报的错误');
})();
\ No newline at end of file \ No newline at end of file
// Sentry 错误上报增强功能示例
const Request = require('../dist/index').default;
const { reportBusinessError } = require('../dist/index');
// 创建请求实例,配置Sentry
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 10000,
appId: 'your-app-id',
appSecret: 'your-app-secret',
sentryDsn: 'https://your-sentry-dsn@sentry.io/project-id',
sentryOptions: {
environment: 'production',
release: 'v1.0.0',
debug: false
},
// 可选:生成唯一请求ID
requestId: `req-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`
});
// 示例1:网络请求错误自动上报
async function demonstrateNetworkErrorReporting() {
console.log('\n示例1: 网络请求错误自动上报');
try {
// 请求一个不存在的API,将触发网络错误
await request.get('/non-existent-api');
} catch (error) {
console.error('网络请求失败:', error.message);
console.log('错误已自动上报到Sentry,包含详细的请求和响应信息');
}
}
// 示例2:业务逻辑错误自动上报
async function demonstrateBusinessErrorReporting() {
console.log('\n示例2: 业务逻辑错误自动上报');
// 模拟API响应中的业务错误
const mockApiResponse = {
status: 200,
statusText: 'OK',
data: {
code: 40001,
message: '用户未授权',
data: null
},
headers: {
'content-type': 'application/json'
},
config: {}
};
// 模拟请求配置
const config = {
url: '/api/user/profile',
method: 'GET',
sentryDsn: 'https://your-sentry-dsn@sentry.io/project-id',
requestId: `req-${Date.now()}`
};
// 手动调用检查业务错误的方法
request.checkBusinessError(mockApiResponse, config);
console.log('业务错误已自动上报到Sentry,错误码:', mockApiResponse.data.code);
}
// 示例3:手动上报业务错误
async function demonstrateManualErrorReporting() {
console.log('\n示例3: 手动上报业务错误');
// 业务数据
const businessData = {
code: 50001,
message: '服务暂时不可用',
requestPath: '/api/payment',
userId: 'user123',
timestamp: new Date().toISOString()
};
// 额外上下文信息
const extraInfo = {
requestContext: {
url: '/api/payment',
method: 'POST',
params: { orderId: 'order123' },
data: { amount: 100, currency: 'CNY' }
},
environment: {
appVersion: '2.1.0',
deviceModel: 'iPhone 13'
}
};
// 上报选项
const options = {
level: 'error',
tags: {
module: 'payment',
feature: 'checkout'
}
};
// 手动上报业务错误
reportBusinessError(
`支付处理错误 [${businessData.code}]: ${businessData.message}`,
businessData,
extraInfo,
options
);
console.log('已手动上报业务错误到Sentry,包含详细的上下文信息');
}
// 运行示例
async function runDemo() {
console.log('===== Sentry 错误上报增强功能示例 =====');
try {
await demonstrateNetworkErrorReporting();
await demonstrateBusinessErrorReporting();
await demonstrateManualErrorReporting();
console.log('\n===== 示例完成 =====');
console.log('查看Sentry控制台以了解上报的错误详情');
} catch (error) {
console.error('示例运行失败:', error);
}
}
runDemo();
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stringify 对比测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
h1 {
color: #333;
text-align: center;
}
.test-case {
border: 1px solid #ddd;
border-radius: 4px;
padding: 15px;
margin: 10px 0;
background-color: #fafafa;
}
.test-title {
font-weight: bold;
color: #2c3e50;
margin-bottom: 10px;
}
.result {
margin: 5px 0;
padding: 8px;
border-radius: 4px;
font-family: monospace;
word-break: break-all;
}
.custom-result {
background-color: #e8f5e8;
border-left: 4px solid #4caf50;
}
.qs-result {
background-color: #e3f2fd;
border-left: 4px solid #2196f3;
}
.diff {
background-color: #ffebee;
border-left: 4px solid #f44336;
color: #d32f2f;
}
.same {
background-color: #f1f8e9;
border-left: 4px solid #8bc34a;
color: #558b2f;
}
.input-data {
background-color: #fff3e0;
border-left: 4px solid #ff9800;
margin-bottom: 10px;
padding: 8px;
font-family: monospace;
}
button {
background-color: #2196f3;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #1976d2;
}
.summary {
background-color: #fff;
border: 2px solid #4caf50;
border-radius: 8px;
padding: 15px;
margin-top: 20px;
}
.warning {
background-color: #fff3cd;
border: 2px solid #ffc107;
color: #856404;
}
.error {
background-color: #f8d7da;
border: 2px solid #dc3545;
color: #721c24;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/qs@6.11.0/dist/qs.min.js"></script>
</head>
<body>
<div class="container">
<h1>🔍 Stringify 函数对比测试</h1>
<p>对比我们自定义的 stringify 函数与 qs.stringify 的差异</p>
<button onclick="runAllTests()">🚀 运行所有测试</button>
<button onclick="clearResults()">🧹 清空结果</button>
<div id="results"></div>
<div id="summary" class="summary" style="display: none;">
<h3>📊 测试总结</h3>
<div id="summaryContent"></div>
</div>
</div>
<script>
// 我们的自定义 stringify 函数
function customStringify(obj, options = {}) {
const {
arrayFormat = 'indices',
allowDots = false,
encodeValuesOnly = false,
encode = true,
delimiter = '&'
} = options;
const pairs = [];
function addPair(key, value, keyPrefix) {
const finalKey = keyPrefix ? `${keyPrefix}${allowDots ? '.' : '['}${key}${allowDots ? '' : ']'}` : key;
if (value === null) {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=null` : `${finalKey}=null`);
} else if (value === undefined) {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=undefined` : `${finalKey}=undefined`);
} else if (typeof value === 'boolean') {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
} else if (typeof value === 'number') {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
let arrayKey;
switch (arrayFormat) {
case 'indices':
arrayKey = `${finalKey}[${index}]`;
break;
case 'brackets':
arrayKey = `${finalKey}[]`;
break;
case 'repeat':
arrayKey = finalKey;
break;
case 'comma':
return;
default:
arrayKey = `${finalKey}[${index}]`;
}
if (typeof item === 'object' && item !== null) {
serializeObject(item, arrayKey);
} else {
const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(arrayKey) : arrayKey;
const encodedValue = encode ? encodeURIComponent(String(item)) : String(item);
pairs.push(`${encodedKey}=${encodedValue}`);
}
});
if (arrayFormat === 'comma' && value.length > 0) {
const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
const encodedValues = value.map(item => encode ? encodeURIComponent(String(item)) : String(item));
pairs.push(`${encodedKey}=${encodedValues.join(',')}`);
}
} else if (typeof value === 'object' && value !== null) {
serializeObject(value, finalKey);
} else {
const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
const encodedValue = encode ? encodeURIComponent(String(value)) : String(value);
pairs.push(`${encodedKey}=${encodedValue}`);
}
}
function serializeObject(obj, prefix) {
Object.keys(obj).forEach(key => {
const value = obj[key];
addPair(key, value, prefix);
});
}
serializeObject(obj);
return pairs.join(delimiter);
}
// 测试用例
const testCases = [
{
name: "基础对象",
data: { name: "张三", age: 25, city: "北京" },
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
},
{
name: "包含数组 - indices 格式",
data: { users: ["alice", "bob", "charlie"], status: "active" },
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
},
{
name: "包含数组 - brackets 格式",
data: { users: ["alice", "bob", "charlie"], status: "active" },
options: { arrayFormat: 'brackets', allowDots: true, encodeValuesOnly: true }
},
{
name: "包含数组 - repeat 格式",
data: { users: ["alice", "bob", "charlie"], status: "active" },
options: { arrayFormat: 'repeat', allowDots: true, encodeValuesOnly: true }
},
{
name: "包含数组 - comma 格式",
data: { users: ["alice", "bob", "charlie"], status: "active" },
options: { arrayFormat: 'comma', allowDots: true, encodeValuesOnly: true }
},
{
name: "嵌套对象 - allowDots: true",
data: { user: { profile: { name: "张三", age: 25 } }, status: "active" },
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
},
{
name: "嵌套对象 - allowDots: false",
data: { user: { profile: { name: "张三", age: 25 } }, status: "active" },
options: { arrayFormat: 'indices', allowDots: false, encodeValuesOnly: true }
},
{
name: "特殊值处理",
data: { nullValue: null, undefinedValue: undefined, boolValue: true, numValue: 42 },
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
},
{
name: "包含特殊字符",
data: { message: "Hello World!", email: "test@example.com", url: "https://example.com?param=value" },
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
},
{
name: "复杂嵌套结构",
data: {
user: {
name: "张三",
tags: ["developer", "javascript"],
settings: { theme: "dark", notifications: true }
},
timestamp: Date.now()
},
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
},
{
name: "签名验证场景模拟",
data: {
appId: "test-app",
timestamp: "1640995200000",
nonce: "abc123",
data: { userId: 123, action: "login" }
},
options: { arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true }
}
];
let testResults = [];
function runTest(testCase, index) {
const { name, data, options } = testCase;
let customResult, qsResult, customError, qsError;
// 测试我们的自定义函数
try {
customResult = customStringify(data, options);
} catch (error) {
customError = error.message;
}
// 测试 qs.stringify
try {
qsResult = Qs.stringify(data, options);
} catch (error) {
qsError = error.message;
}
const isEqual = customResult === qsResult;
const result = {
name,
data,
options,
customResult,
qsResult,
customError,
qsError,
isEqual
};
testResults.push(result);
displayTestResult(result, index);
return result;
}
function displayTestResult(result, index) {
const resultsDiv = document.getElementById('results');
const testDiv = document.createElement('div');
testDiv.className = 'test-case';
const statusClass = result.isEqual ? 'same' : 'diff';
const statusText = result.isEqual ? '✅ 相同' : '❌ 不同';
testDiv.innerHTML = `
<div class="test-title">${index + 1}. ${result.name} - ${statusText}</div>
<div class="input-data">
<strong>输入数据:</strong> ${JSON.stringify(result.data)}<br>
<strong>选项:</strong> ${JSON.stringify(result.options)}
</div>
<div class="result custom-result">
<strong>我们的 stringify:</strong> ${result.customError || result.customResult || 'undefined'}
</div>
<div class="result qs-result">
<strong>qs.stringify:</strong> ${result.qsError || result.qsResult || 'undefined'}
</div>
<div class="result ${statusClass}">
<strong>对比结果:</strong> ${statusText}
${!result.isEqual ? '<br><strong>⚠️ 发现差异!这可能导致签名验证失败</strong>' : ''}
</div>
`;
resultsDiv.appendChild(testDiv);
}
function runAllTests() {
clearResults();
testResults = [];
testCases.forEach((testCase, index) => {
runTest(testCase, index);
});
showSummary();
}
function clearResults() {
document.getElementById('results').innerHTML = '';
document.getElementById('summary').style.display = 'none';
testResults = [];
}
function showSummary() {
const summaryDiv = document.getElementById('summary');
const summaryContent = document.getElementById('summaryContent');
const totalTests = testResults.length;
const passedTests = testResults.filter(r => r.isEqual).length;
const failedTests = totalTests - passedTests;
let summaryClass = 'summary';
let summaryIcon = '✅';
let riskLevel = '低风险';
if (failedTests > 0) {
summaryClass += ' warning';
summaryIcon = '⚠️';
riskLevel = '中等风险';
if (failedTests > totalTests * 0.5) {
summaryClass = 'summary error';
summaryIcon = '❌';
riskLevel = '高风险';
}
}
summaryDiv.className = summaryClass;
const failedTestsList = testResults
.filter(r => !r.isEqual)
.map(r => `<li><strong>${r.name}</strong>: 可能影响签名验证</li>`)
.join('');
summaryContent.innerHTML = `
<h4>${summaryIcon} 测试完成</h4>
<p><strong>总测试数:</strong> ${totalTests}</p>
<p><strong>通过:</strong> ${passedTests}</p>
<p><strong>失败:</strong> ${failedTests}</p>
<p><strong>兼容性风险等级:</strong> ${riskLevel}</p>
${failedTests > 0 ? `
<h4>🚨 发现的差异:</h4>
<ul>${failedTestsList}</ul>
<h4>💡 建议:</h4>
<ul>
<li>如果之前使用 qs.stringify,建议保持使用以确保向后兼容</li>
<li>如果必须使用自定义 stringify,需要更新现有签名验证逻辑</li>
<li>考虑添加兼容性层来处理两种格式</li>
</ul>
` : `
<h4>🎉 完全兼容!</h4>
<p>我们的 stringify 函数与 qs.stringify 完全兼容,可以安全替换。</p>
`}
`;
summaryDiv.style.display = 'block';
}
// 页面加载完成后自动运行测试
window.onload = function() {
console.log('页面加载完成,准备运行 stringify 对比测试...');
};
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
// UniApp 环境 - ES 模块格式兼容性测试
// 使用 ES 模块格式导入
import { Request, generateSignature, verifySignature } from '../dist/index.esm.js';
console.log('=== UniApp ES 模块格式兼容性测试 ===');
// 测试模块导入
console.log('1. 模块导入测试:');
console.log('Request 类:', typeof Request);
console.log('generateSignature 函数:', typeof generateSignature);
console.log('verifySignature 函数:', typeof verifySignature);
// 测试基本实例化
console.log('\n2. 实例化测试:');
try {
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
console.log('✅ Request 实例化成功');
console.log('实例类型:', typeof request);
console.log('实例方法:', Object.getOwnPropertyNames(Object.getPrototypeOf(request)));
} catch (error) {
console.error('❌ Request 实例化失败:', error.message);
}
// 测试签名功能
console.log('\n3. 签名功能测试:');
try {
const signatureOptions = {
appId: 'uniapp-test-id',
appSecret: 'uniapp-test-secret',
params: {
platform: 'uniapp',
version: '1.0.0',
data: {
userId: 12345,
action: 'getData'
}
}
};
const signature = generateSignature(signatureOptions);
console.log('✅ 签名生成成功');
console.log('签名结果:', signature);
// 验证签名
const isValid = verifySignature({
...signatureOptions,
signature: signature.signature,
timestamp: signature.timestamp,
nonce: signature.nonce
});
console.log('✅ 签名验证结果:', isValid);
} catch (error) {
console.error('❌ 签名功能测试失败:', error.message);
}
// 测试 UniApp 特定配置
console.log('\n4. UniApp 特定配置测试:');
try {
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'UniApp/1.0.0'
},
// UniApp 特定配置
adapter: 'uniapp',
enableHttp2: true,
enableQuic: true
});
console.log('✅ UniApp 特定配置创建成功');
// 测试请求配置
const config = {
url: '/uniapp/test',
method: 'POST',
data: {
platform: 'uniapp',
test: 'data'
},
header: {
'X-Platform': 'UniApp'
}
};
console.log('✅ UniApp 请求配置创建成功');
console.log('配置对象:', config);
} catch (error) {
console.error('❌ UniApp 配置测试失败:', error.message);
}
// 测试异步/await 语法支持
console.log('\n5. 异步语法支持测试:');
async function testAsyncSupport() {
try {
const request = new Request({
baseURL: 'https://api.example.com'
});
console.log('✅ 异步函数中实例化成功');
// 模拟异步操作
const mockResponse = await new Promise(resolve => {
setTimeout(() => {
resolve({
data: { message: 'UniApp 异步测试成功' },
status: 200
});
}, 100);
});
console.log('✅ 异步操作测试成功:', mockResponse);
} catch (error) {
console.error('❌ 异步语法测试失败:', error.message);
}
}
// 运行异步测试
testAsyncSupport();
// 测试 UniApp 生命周期兼容性
console.log('\n6. UniApp 生命周期兼容性测试:');
const uniappPageConfig = {
data() {
return {
request: null,
loading: false,
result: null
};
},
onLoad() {
console.log('✅ UniApp onLoad 生命周期');
this.initRequest();
},
onShow() {
console.log('✅ UniApp onShow 生命周期');
},
methods: {
initRequest() {
try {
this.request = new Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
console.log('✅ UniApp 页面中 Request 初始化成功');
} catch (error) {
console.error('❌ UniApp 页面中 Request 初始化失败:', error.message);
}
},
async fetchData() {
this.loading = true;
try {
// 模拟请求
const response = await new Promise(resolve => {
setTimeout(() => {
resolve({
data: { message: 'UniApp 数据获取成功' },
statusCode: 200
});
}, 200);
});
this.result = response.data;
console.log('✅ UniApp 数据获取成功:', response);
} catch (error) {
console.error('❌ UniApp 数据获取失败:', error.message);
} finally {
this.loading = false;
}
}
}
};
console.log('✅ UniApp 页面配置创建成功');
console.log('页面配置:', Object.keys(uniappPageConfig));
console.log('\n=== UniApp ES 模块格式兼容性测试完成 ===');
// 导出配置供 UniApp 使用
export default uniappPageConfig;
\ No newline at end of file \ No newline at end of file
// uniapp环境下使用 Sentry 的示例
import { Request } from '../dist';
// 创建请求实例,并配置 Sentry
const request = new Request({
baseURL: 'https://api.example.com',
// Sentry 配置 - 在uniapp环境中会自动使用 sentry-miniapp.js
sentryDsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
sentryOptions: {
environment: 'uniapp',
debug: true,
tracesSampleRate: 1.0
}
});
// 发起请求
function fetchData() {
return request.request({
url: '/api/data',
method: 'GET'
}).then(response => {
console.log('请求成功:', response);
return response;
}).catch(error => {
console.error('请求失败:', error);
// 错误会自动上报到 Sentry
throw error;
});
}
export default {
data() {
return {
result: null,
loading: false,
error: null
};
},
onLoad() {
this.loadData();
},
methods: {
loadData() {
this.loading = true;
this.error = null;
fetchData()
.then(response => {
this.result = response.data;
this.loading = false;
})
.catch(error => {
this.error = error.message;
this.loading = false;
});
}
}
};
\ No newline at end of file \ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>UniApp UMD 格式兼容性测试</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="app">
<h1>UniApp UMD 格式兼容性测试</h1>
<div id="test-results"></div>
<button onclick="runTests()">运行测试</button>
</div>
<!-- 加载 UMD 格式的库 -->
<script src="../dist/index.umd.js"></script>
<script>
console.log('=== UniApp UMD 格式兼容性测试 ===');
// 模拟 UniApp 环境
window.uni = {
request: function(options) {
console.log('模拟 uni.request 调用:', options);
return new Promise((resolve, reject) => {
setTimeout(() => {
if (options.url.includes('error')) {
reject({
errMsg: '模拟请求失败',
statusCode: 500
});
} else {
resolve({
data: { message: 'UniApp 模拟请求成功', timestamp: Date.now() },
statusCode: 200,
header: { 'Content-Type': 'application/json' }
});
}
}, 300);
});
},
showToast: function(options) {
console.log('模拟 uni.showToast:', options.title);
const toast = document.createElement('div');
toast.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#000;color:#fff;padding:10px;border-radius:5px;z-index:9999;';
toast.textContent = options.title;
document.body.appendChild(toast);
setTimeout(() => document.body.removeChild(toast), options.duration || 1500);
},
getSystemInfo: function() {
return {
platform: 'uniapp',
system: 'test',
version: '1.0.0'
};
}
};
function logResult(message, isSuccess = true) {
const resultsDiv = document.getElementById('test-results');
const p = document.createElement('p');
p.style.color = isSuccess ? 'green' : 'red';
p.textContent = (isSuccess ? '✅ ' : '❌ ') + message;
resultsDiv.appendChild(p);
console.log(message);
}
function runTests() {
const resultsDiv = document.getElementById('test-results');
resultsDiv.innerHTML = '';
// 测试全局对象
console.log('1. 全局对象测试:');
if (typeof window.GlskFetch !== 'undefined') {
logResult('GlskFetch 全局对象存在');
console.log('GlskFetch 对象:', window.GlskFetch);
console.log('可用方法:', Object.keys(window.GlskFetch));
} else {
logResult('GlskFetch 全局对象不存在', false);
return;
}
// 测试解构赋值
console.log('\n2. 解构赋值测试:');
try {
const { Request, generateSignature, verifySignature } = window.GlskFetch;
logResult('解构赋值成功');
console.log('Request:', typeof Request);
console.log('generateSignature:', typeof generateSignature);
console.log('verifySignature:', typeof verifySignature);
} catch (error) {
logResult('解构赋值失败: ' + error.message, false);
return;
}
// 测试实例化
console.log('\n3. 实例化测试:');
try {
const { Request } = window.GlskFetch;
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'UniApp/UMD-Test'
}
});
logResult('Request 实例化成功');
console.log('实例:', request);
} catch (error) {
logResult('Request 实例化失败: ' + error.message, false);
}
// 测试签名功能
console.log('\n4. 签名功能测试:');
try {
const { generateSignature, verifySignature } = window.GlskFetch;
const signatureOptions = {
appId: 'uniapp-umd-test',
appSecret: 'uniapp-umd-secret',
params: {
platform: 'uniapp-umd',
version: '1.0.0',
systemInfo: uni.getSystemInfo(),
data: {
userId: 67890,
action: 'testUMD'
}
}
};
const signature = generateSignature(signatureOptions);
logResult('签名生成成功');
console.log('签名结果:', signature);
// 验证签名
const isValid = verifySignature({
...signatureOptions,
signature: signature.signature,
timestamp: signature.timestamp,
nonce: signature.nonce
});
logResult('签名验证结果: ' + isValid);
} catch (error) {
logResult('签名功能测试失败: ' + error.message, false);
}
// 测试 UniApp 环境适配
console.log('\n5. UniApp 环境适配测试:');
testUniAppIntegration();
}
async function testUniAppIntegration() {
try {
const { Request } = window.GlskFetch;
// 创建适配 UniApp 的请求实例
const request = new Request({
baseURL: 'https://api.example.com',
timeout: 10000,
// 模拟 UniApp 特定配置
adapter: function(config) {
console.log('使用 UniApp 适配器:', config);
return uni.request({
url: config.baseURL + config.url,
method: config.method || 'GET',
data: config.data,
header: config.headers,
timeout: config.timeout,
success: function(res) {
config.resolve && config.resolve(res);
},
fail: function(err) {
config.reject && config.reject(err);
}
});
}
});
logResult('UniApp 适配器配置成功');
// 模拟请求测试
console.log('开始模拟请求测试...');
try {
const response = await uni.request({
url: 'https://api.example.com/uniapp/test',
method: 'POST',
data: {
platform: 'uniapp',
format: 'umd',
timestamp: Date.now()
}
});
logResult('UniApp 请求测试成功');
console.log('响应数据:', response);
// 显示成功提示
uni.showToast({
title: 'UniApp UMD 测试成功',
duration: 2000
});
} catch (error) {
logResult('UniApp 请求测试失败: ' + error.errMsg, false);
}
} catch (error) {
logResult('UniApp 环境适配测试失败: ' + error.message, false);
}
}
// 测试 UniApp 页面生命周期
console.log('\n6. UniApp 页面生命周期模拟:');
const uniappPage = {
data: {
request: null,
loading: false,
testResults: []
},
onLoad: function() {
console.log('模拟 UniApp onLoad');
this.initRequest();
logResult('UniApp onLoad 生命周期模拟成功');
},
onShow: function() {
console.log('模拟 UniApp onShow');
logResult('UniApp onShow 生命周期模拟成功');
},
onReady: function() {
console.log('模拟 UniApp onReady');
this.runPageTests();
logResult('UniApp onReady 生命周期模拟成功');
},
initRequest: function() {
try {
const { Request } = window.GlskFetch;
this.data.request = new Request({
baseURL: 'https://api.example.com',
timeout: 5000
});
logResult('页面中 Request 初始化成功');
} catch (error) {
logResult('页面中 Request 初始化失败: ' + error.message, false);
}
},
runPageTests: function() {
console.log('运行页面级测试...');
// 测试数据绑定
this.data.testResults.push('UMD 格式加载成功');
this.data.testResults.push('UniApp 环境模拟成功');
this.data.testResults.push('页面生命周期正常');
logResult('页面级测试完成,结果数量: ' + this.data.testResults.length);
}
};
// 模拟页面生命周期
setTimeout(() => {
uniappPage.onLoad();
setTimeout(() => {
uniappPage.onShow();
setTimeout(() => {
uniappPage.onReady();
}, 100);
}, 100);
}, 500);
console.log('\n=== UniApp UMD 格式兼容性测试准备完成 ===');
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
...@@ -58,8 +58,8 @@ ...@@ -58,8 +58,8 @@
<div class="card"> <div class="card">
<h2>测试说明</h2> <h2>测试说明</h2>
<p>本页面测试在请求前检查method参数是否在白名单中,如果在白名单中,则在URL中添加sdctag=true参数并参与签名。</p> <p>本页面测试在请求前检查method参数是否在白名单中,如果在白名单中,则在URL中添加sdctag=true参数并参与签名。</p>
<button id="testWhitelist">测试白名单内请求</button> <button id="testWhitelist">测试GET请求</button>
<button id="testNonWhitelist">测试白名单外请求</button> <button id="testNonWhitelist">测试POST请求</button>
<h3>结果:</h3> <h3>结果:</h3>
<pre id="result">点击按钮开始测试...</pre> <pre id="result">点击按钮开始测试...</pre>
</div> </div>
...@@ -117,7 +117,9 @@ ...@@ -117,7 +117,9 @@
const result = await request.get('/dict/sign/test', { const result = await request.get('/dict/sign/test', {
params:{ params:{
"id":6, "id":6,
"objs": ["hehe", "haah"] "objs": ["hehe", "haah"],
"dogs":[{"name":"haogou","age":1},{"name":"拉布拉多","age":2}],
"dogs":{"name":"haogou","age":1}
} }
}); });
...@@ -135,9 +137,11 @@ ...@@ -135,9 +137,11 @@
// 白名单URL列表由SDK内部处理 // 白名单URL列表由SDK内部处理
// 我们只需要在请求参数中添加method参数 // 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数'); console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');
const result = await request.post('/dict/sign/test2', { const result = await request.post('/dict/sign/test1', {
"id":6, "id":6,
"objs": ["hehe", "haah"] "objs": ["hehe", "haah"],
"dogs":[{"name":"haogou","age":1},{"name":"拉布拉多","age":2}],
"dog":{"name":"haogou","age":1}
}); });
resultElement.textContent = resultElement.textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`; `请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
......
<!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);
}
.button-group {
display: flex;
gap: 10px;
margin-top: 10px;
}
button {
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
pre {
background-color: #f5f5f5;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}
</style>
</head>
<body>
<h1>白名单URL测试</h1>
<div class="container">
<div class="card">
<h2>测试说明</h2>
<p>本页面测试在请求前检查method参数是否在白名单中,如果在白名单中,则在URL中添加sdctag=true参数并参与签名。</p>
</div>
<div class="card">
<h2>白名单URL</h2>
<pre id="whitelist">加载中...</pre>
<div class="button-group">
<button id="refreshWhitelist">刷新白名单</button>
<button id="clearCache">清除缓存</button>
</div>
</div>
<div class="card">
<h2>测试请求</h2>
<div class="button-group">
<button id="testInWhitelist">测试白名单内请求</button>
<button id="testNotInWhitelist">测试白名单外请求</button>
</div>
<h3>请求结果</h3>
<pre id="result">点击上方按钮发起测试请求</pre>
</div>
</div>
<script>
// 使用全局变量
const Request = window.GlskFetch.default;
// 创建模拟的Trace对象
const Trace = {
urls: ['user.get.info', 'order.create', 'product.list'],
getTraceUrls: async function(forceRefresh = false) {
console.log('获取白名单URL列表');
return this.urls;
},
clearCache: function() {
console.log('清除白名单缓存');
},
preloadTraceUrls: async function() {
console.log('预加载白名单URL列表');
return this.urls;
},
isPreloaded: true
};
// 创建请求实例
const request = new Request({
baseURL: 'https://jsonplaceholder.typicode.com',
appId: 'test-app-id',
appSecret: 'test-app-secret',
timeout: 10000,
sentryDsn: 'https://example@sentry.io/123456', // 提供一个示例Sentry DSN
disableSentry: true // 禁用Sentry,避免实际发送错误报告
});
// 模拟白名单URL已在Trace对象中定义
// 显示当前白名单
async function displayWhitelist() {
const whitelist = await Trace.getTraceUrls();
document.getElementById('whitelist').textContent = JSON.stringify(whitelist, null, 2);
}
// 初始化显示白名单
displayWhitelist();
// 刷新白名单按钮
document.getElementById('refreshWhitelist').addEventListener('click', () => {
displayWhitelist();
});
// 清除缓存按钮
document.getElementById('clearCache').addEventListener('click', () => {
Trace.clearCache();
displayWhitelist();
});
// 测试白名单内请求
document.getElementById('testInWhitelist').addEventListener('click', async () => {
try {
const result = await request.get('/posts/1', {
method: 'user.get.info' // 白名单内的method
});
document.getElementById('result').textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
} catch (error) {
document.getElementById('result').textContent = `请求失败: ${error.message}`;
}
});
// 测试白名单外请求
document.getElementById('testNotInWhitelist').addEventListener('click', async () => {
try {
const result = await request.get('/posts/1', {
method: 'user.delete.account' // 白名单外的method
});
document.getElementById('result').textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
} catch (error) {
document.getElementById('result').textContent = `请求失败: ${error.message}`;
}
});
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
...@@ -3,6 +3,7 @@ import commonjs from '@rollup/plugin-commonjs'; ...@@ -3,6 +3,7 @@ import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel'; import babel from '@rollup/plugin-babel';
import terser from '@rollup/plugin-terser'; import terser from '@rollup/plugin-terser';
import typescript from '@rollup/plugin-typescript'; import typescript from '@rollup/plugin-typescript';
import nodePolyfills from 'rollup-plugin-polyfill-node';
const extensions = ['.ts']; const extensions = ['.ts'];
...@@ -21,11 +22,18 @@ export default { ...@@ -21,11 +22,18 @@ export default {
plugins: [ plugins: [
// 允许 node_modules 中的包被解析 // 允许 node_modules 中的包被解析
resolve({ extensions }), resolve({
extensions,
browser: true,
preferBuiltins: false
}),
// 将 CommonJS 模块转换为 ES6 // 将 CommonJS 模块转换为 ES6
commonjs(), commonjs(),
// 添加 Node.js polyfills 支持浏览器环境
nodePolyfills(),
// 编译TypeScript // 编译TypeScript
typescript(), typescript(),
......
import type { RequestConfig } from '../types'; import { processParams, ArrayProcessMode } from '../utils';
/** /**
* 构建完整URL * 构建完整URL
...@@ -14,24 +14,12 @@ export function buildURL(baseURL: string = '', url: string = '', params: Record< ...@@ -14,24 +14,12 @@ export function buildURL(baseURL: string = '', url: string = '', params: Record<
// 处理GET请求参数或其他方法的URL参数 // 处理GET请求参数或其他方法的URL参数
if ((method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') && Object.keys(params).length) { if ((method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') && Object.keys(params).length) {
const queryParts: string[] = []; // 使用通用参数处理函数,采用对象索引模式处理数组,支持Java后端
const processedParams = processParams(params, ArrayProcessMode.OBJECT_INDEX) as Array<{key: string, value: string}>;
// 遍历所有参数 // 构建查询字符串
Object.keys(params).forEach(key => { const queryParts = processedParams.map(({ key, value }) =>
const value = params[key]; `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
);
// 处理数组参数
if (Array.isArray(value)) {
// 对于数组,使用索引格式 key[0]=value, key[1]=value
value.forEach((item, index) => {
queryParts.push(`${encodeURIComponent(key)}[${index}]=${encodeURIComponent(item)}`);
});
} else {
// 对于非数组参数,正常处理
queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
});
const queryString = queryParts.join('&'); const queryString = queryParts.join('&');
fullURL += (fullURL.includes('?') ? '&' : '?') + queryString; fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
} }
......
import Request from './request'; import Request from './request';
import Defaults from './defaults'; import Defaults from './defaults';
import * as Sentry from './sentry'; import * as Sentry from './sentry';
import { generateSignature, verifySignature } from './signature';
// 导出主类 // 导出主类
export default Request; export default Request;
// 导出 Defaults 类,方便用户直接使用 // 导出 Defaults 类,方便用户直接使用
export { Defaults, Sentry }; export { Defaults, Sentry };
// 导出签名函数
export { generateSignature, verifySignature };
// 导出类型定义 // 导出类型定义
export type { RequestConfig, ResponseData, RequestHeaders } from './types'; export type { RequestConfig, ResponseData, RequestHeaders } from './types';
export type { SentryOptions, ErrorReportOptions } from './sentry'; export type { SentryOptions, ErrorReportOptions } from './sentry';
\ No newline at end of file \ No newline at end of file
export type { SignatureOptions, SignatureResult } from './signature';
\ No newline at end of file \ No newline at end of file
...@@ -201,6 +201,7 @@ class Request { ...@@ -201,6 +201,7 @@ class Request {
appId, appId,
appSecret, appSecret,
params: signatureParams, params: signatureParams,
method: config.method || 'GET',
}); });
// 添加签名到请求头 // 添加签名到请求头
config.headers = { config.headers = {
......
import CryptoJS from 'crypto-js'; import CryptoJS from 'crypto-js';
import { stringify } from './libs'; import { stringify } from './libs';
import { processGetSignatureParams, processPostSignatureParams } from './utils';
export interface SignatureOptions { export interface SignatureOptions {
appId: string; appId: string;
appSecret: string; appSecret: string;
params?: Record<string, any>; params?: Record<string, any>;
noSignAttr?: string[]; noSignAttr?: string[];
method?: string;
} }
export interface SignatureResult { export interface SignatureResult {
...@@ -16,11 +18,26 @@ export interface SignatureResult { ...@@ -16,11 +18,26 @@ export interface SignatureResult {
} }
/** /**
* 生成UUID * 生成UUID v4格式的随机字符串
* @returns {string} UUID * 使用更高效的实现方式
* @returns {string} UUID v4格式字符串
*/ */
function generateUUID(): string { function generateUUID(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { // 使用crypto API如果可用,否则回退到Math.random
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
// 设置版本号 (4) 和变体位
bytes[6] = (bytes[6] & 0x0f) | 0x40; // 版本4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // 变体位
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
// 回退到原有实现
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0; const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8); const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16); return v.toString(16);
...@@ -28,82 +45,82 @@ function generateUUID(): string { ...@@ -28,82 +45,82 @@ function generateUUID(): string {
} }
/** /**
* 验证签名参数
* @param options 签名选项
*/
function validateSignatureOptions(options: SignatureOptions): void {
if (!options) {
throw new Error('Signature options are required');
}
const { appId, appSecret, method } = options;
if (!appId || typeof appId !== 'string' || appId.trim() === '') {
throw new Error('Valid appId is required');
}
if (!appSecret || typeof appSecret !== 'string' || appSecret.trim() === '') {
throw new Error('Valid appSecret is required');
}
if (method && typeof method !== 'string') {
throw new Error('Method must be a string');
}
}
/**
* 构建签名字符串
* @param processedParams 处理后的参数
* @param noSignAttr 不参与签名的属性列表
* @returns 签名字符串
*/
function buildSignatureString(processedParams: Record<string, any>, noSignAttr: string[]): string {
return Object.keys(processedParams)
.sort()
.filter(key => !noSignAttr.includes(key))
.map(key => `${key}=${processedParams[key]}`)
.join('&');
}
/**
* 生成签名 * 生成签名
* @param {Object} options 签名参数 * @param options 签名参数
* @param {string} options.appId 应用ID * @returns 签名信息
* @param {string} options.appSecret 应用密钥
* @param {Object} options.params 请求参数
* @returns {Object} 签名信息
*/ */
export function generateSignature(options: SignatureOptions): SignatureResult { export function generateSignature(options: SignatureOptions): SignatureResult {
// 参数验证
validateSignatureOptions(options);
const { const {
appId, appId,
appSecret, appSecret,
params = {}, params = {},
noSignAttr = [] noSignAttr = [],
method = 'GET'
} = options; } = options;
if (!appId || !appSecret) { // 生成随机字符串和时间戳
throw new Error('appId and appSecret are required');
}
// 生成随机字符串
const nonce = generateUUID(); const nonce = generateUUID();
// 生成时间戳
const timestamp = Date.now().toString(); const timestamp = Date.now().toString();
// 准备签名参数,先添加系统参数 // 准备签名参数,先添加系统参数
const allParams = { const allParams: Record<string, any> = {
'X-App-Id': appId, 'X-App-Id': appId,
'X-Nonce': nonce, 'X-Nonce': nonce,
'X-Timestamp': timestamp, 'X-Timestamp': timestamp,
...params ...params
}; };
// 1. 使用 stringify 序列化参数 // 根据请求方法使用相应的参数处理函数
const objStr = stringify(allParams, { const normalizedMethod = method.toUpperCase();
arrayFormat: 'indices', const processedParams = normalizedMethod === 'GET'
allowDots: true, ? processGetSignatureParams(allParams)
encodeValuesOnly: true : processPostSignatureParams(allParams);
});
// 2. 解析查询字符串
const objVal = objStr.split('&');
const realObj: Record<string, any> = {};
objVal.forEach(item => {
const idx = item.indexOf('=');
if (idx !== -1) {
const key = item.split('=')[0];
const value = decodeURIComponent(item.slice(idx + 1));
realObj[key] = value;
}
});
// 3. 处理特殊值和对象类型
const keys = Object.keys(realObj).sort();
for (const key in realObj) { // 构建签名字符串
let obj = realObj[key]; const stringToSign = buildSignatureString(processedParams, noSignAttr);
if (obj === null) {
obj = '';
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
// 4. 排除不参与签名的属性,并拼接签名字符串 // 生成最终签名
const str: string[] = [];
keys.forEach(e => {
if (!noSignAttr.includes(e)) {
str.push(`${e}=${realObj[e]}`);
}
});
// 5. 拼接应用密钥并生成签名
const stringToSign = str.join('&');
const signString = `${stringToSign}&secret=${appSecret}`; const signString = `${stringToSign}&secret=${appSecret}`;
const sign = CryptoJS.HmacSHA256(signString, appSecret).toString(); const sign = CryptoJS.HmacSHA256(signString, appSecret).toString();
...@@ -113,81 +130,3 @@ export function generateSignature(options: SignatureOptions): SignatureResult { ...@@ -113,81 +130,3 @@ export function generateSignature(options: SignatureOptions): SignatureResult {
sign sign
}; };
} }
\ No newline at end of file \ No newline at end of file
/**
* 验证签名
* @param {string} options.appId 应用ID
* @param {string} options.appSecret 应用密钥
* @param {Object} options.params 请求参数
* @returns {boolean} 验证结果
*/
export function verifySignature(options: SignatureOptions): boolean {
const {
appId,
appSecret,
params = {},
noSignAttr = []
} = options;
if (!appId || !appSecret) {
throw new Error('appId and appSecret are required');
}
// 获取传入的签名
const receivedSign = params.sign;
if (!receivedSign) {
return false;
}
// 创建用于验证的参数副本(排除 sign 参数)
const verifyParams = { ...params };
delete verifyParams.sign;
// 1. 使用 stringify 序列化参数
const objStr = stringify(verifyParams, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
});
// 2. 解析查询字符串
const objVal = objStr.split('&');
const realObj: Record<string, any> = {};
objVal.forEach(item => {
const idx = item.indexOf('=');
if (idx !== -1) {
const key = item.split('=')[0];
const value = decodeURIComponent(item.slice(idx + 1));
realObj[key] = value;
}
});
// 3. 处理特殊值和对象类型
const keys = Object.keys(realObj).sort();
for (const key in realObj) {
let obj = realObj[key];
if (obj === null) {
obj = '';
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
// 4. 排除不参与签名的属性,并拼接签名字符串
const str: string[] = [];
keys.forEach(e => {
if (!noSignAttr.includes(e)) {
str.push(`${e}=${realObj[e]}`);
}
});
// 5. 拼接应用密钥并生成签名
const stringToSign = str.join('&');
const signString = `${stringToSign}&secret=${appSecret}`;
const expectedSign = CryptoJS.HmacSHA256(signString, appSecret).toString();
return receivedSign === expectedSign;
}
\ No newline at end of file \ No newline at end of file
...@@ -41,3 +41,170 @@ export const detectEnvironment = (() => { ...@@ -41,3 +41,170 @@ export const detectEnvironment = (() => {
return detectedEnv; return detectedEnv;
}; };
})(); })();
/**
* 数组处理模式枚举
*/
export enum ArrayProcessMode {
/** JSON 格式:将数组转换为 JSON 字符串 */
JSON = 'json',
/** 索引格式:将数组转换为索引键值对 */
INDEX = 'index',
/** 对象索引格式:将对象数组转换为扁平化的索引键值对,适用于Java后端 */
OBJECT_INDEX = 'object_index'
}
/**
* 将参数处理为JSON格式,用于签名计算
* @param params 原始参数对象
* @returns 处理后的参数对象,数组和对象转换为JSON字符串
*/
export function processParamsAsJson(params: Record<string, any>): Record<string, string> {
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result[key] = '';
} else if (Array.isArray(value)) {
// 数组直接转换为 JSON 字符串
result[key] = JSON.stringify(value);
} else if (typeof value === 'object') {
// 对象转换为 JSON 字符串
result[key] = JSON.stringify(value);
} else {
// 基本类型直接使用
result[key] = String(value);
}
}
return result;
}
/**
* 将参数处理为索引格式,用于URL查询参数
* @param params 原始参数对象
* @returns 键值对数组,数组使用索引格式 key[0]=value, key[1]=value
*/
export function processParamsAsIndex(params: Record<string, any>): Array<{key: string, value: string}> {
const result: Array<{key: string, value: string}> = [];
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result.push({ key, value: '' });
} else if (Array.isArray(value)) {
// 数组使用索引格式 key[0]=value, key[1]=value
value.forEach((item, index) => {
result.push({
key: `${key}[${index}]`,
value: String(item)
});
});
} else if (typeof value === 'object') {
// 对象转换为 JSON 字符串
result.push({ key, value: JSON.stringify(value) });
} else {
// 基本类型直接使用
result.push({ key, value: String(value) });
}
}
return result;
}
/**
* 将参数处理为对象索引格式,将对象数组扁平化为Java后端期望的格式
* @param params 原始参数对象
* @returns 键值对数组,对象数组扁平化为 dogs[0].name=value, dogs[0].age=value 格式
*/
export function processParamsAsObjectIndex(params: Record<string, any>): Array<{key: string, value: string}> {
const result: Array<{key: string, value: string}> = [];
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result.push({ key, value: '' });
} else if (Array.isArray(value)) {
// 数组中的每个元素
value.forEach((item, index) => {
if (typeof item === 'object' && item !== null) {
// 对象数组:dogs[0].name=value, dogs[0].age=value
for (const [objKey, objValue] of Object.entries(item)) {
result.push({
key: `${key}[${index}].${objKey}`,
value: String(objValue)
});
}
} else {
// 基本类型数组:key[0]=value, key[1]=value
result.push({
key: `${key}[${index}]`,
value: String(item)
});
}
});
} else if (typeof value === 'object') {
// 单个对象:展开为多个键值对
for (const [objKey, objValue] of Object.entries(value)) {
result.push({
key: `${key}.${objKey}`,
value: String(objValue)
});
}
} else {
// 基本类型直接使用
result.push({ key, value: String(value) });
}
}
return result;
}
/**
* 通用参数处理函数,支持不同的数组处理模式
* @param params 原始参数对象
* @param arrayMode 数组处理模式
* @returns 处理后的参数对象或键值对数组
* @deprecated 建议使用具体的处理函数:processParamsAsJson, processParamsAsIndex, processParamsAsObjectIndex
*/
export function processParams(
params: Record<string, any>,
arrayMode: ArrayProcessMode = ArrayProcessMode.JSON
): Record<string, string> | Array<{key: string, value: string}> {
if (arrayMode === ArrayProcessMode.INDEX) {
return processParamsAsIndex(params);
}
else if (arrayMode === ArrayProcessMode.OBJECT_INDEX) {
return processParamsAsObjectIndex(params);
}
else {
return processParamsAsJson(params);
}
}
/**
* 处理GET请求的签名参数,将数组展开为 key[index]=value 格式
* @param params 原始参数对象
* @returns 处理后的参数对象
*/
export function processGetSignatureParams(params: Record<string, any>): Record<string, string> {
const processedResult = processParams(params, ArrayProcessMode.OBJECT_INDEX);
// OBJECT_INDEX 模式返回的是数组,需要转换为对象
const result: Record<string, string> = {};
(processedResult as Array<{key: string, value: string}>).forEach(item => {
result[item.key] = item.value;
});
return result;
}
/**
* 处理POST请求的签名参数,将数组转换为JSON字符串格式
* @param params 原始参数对象
* @returns 处理后的参数对象
*/
export function processPostSignatureParams(params: Record<string, any>): Record<string, string> {
const processedResult = processParams(params, ArrayProcessMode.JSON);
// JSON 模式直接返回对象
return processedResult as Record<string, string>;
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!