Commit c078e635 by liimin

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

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

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

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

chore(examples): 移除过时的示例文件
1 parent 04d7d083
// 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
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
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
// 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
...@@ -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>
...@@ -116,9 +116,11 @@ ...@@ -116,9 +116,11 @@
// 使用params包裹GET请求参数 // 使用params包裹GET请求参数
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}
}
}); });
resultElement.textContent = resultElement.textContent =
...@@ -135,10 +137,12 @@ ...@@ -135,10 +137,12 @@
// 白名单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)}`;
} catch (error) { } catch (error) {
......
<!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 { SignatureOptions, SignatureResult } from './signature';
\ No newline at end of file \ No newline at end of file
export type { SentryOptions, ErrorReportOptions } from './sentry';
\ 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(); const stringToSign = buildSignatureString(processedParams, noSignAttr);
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 signString = `${stringToSign}&secret=${appSecret}`;
const sign = CryptoJS.HmacSHA256(signString, appSecret).toString(); const sign = CryptoJS.HmacSHA256(signString, appSecret).toString();
...@@ -112,82 +129,4 @@ export function generateSignature(options: SignatureOptions): SignatureResult { ...@@ -112,82 +129,4 @@ export function generateSignature(options: SignatureOptions): SignatureResult {
timestamp, timestamp,
sign sign
}; };
}
/**
* 验证签名
* @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
...@@ -40,4 +40,171 @@ export const detectEnvironment = (() => { ...@@ -40,4 +40,171 @@ export const detectEnvironment = (() => {
return detectedEnv; return detectedEnv;
}; };
})();
\ No newline at end of file \ No newline at end of file
})();
/**
* 数组处理模式枚举
*/
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!