Commit 19ae5ac2 by liimin

feat(example): 添加表单数据测试页面用于演示不同POST格式

添加一个示例HTML页面,用于测试和演示JSON和表单格式的POST请求功能。页面包含两个测试面板,分别展示不同Content-Type的请求结果。
1 parent 228a250e
<!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
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
...@@ -12,23 +13,27 @@ ...@@ -12,23 +13,27 @@
margin: 0 auto; margin: 0 auto;
padding: 20px; padding: 20px;
} }
.container { .container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 20px; gap: 20px;
} }
.card { .card {
border: 1px solid #ddd; border: 1px solid #ddd;
border-radius: 8px; border-radius: 8px;
padding: 15px; padding: 15px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
} }
pre { pre {
background-color: #f5f5f5; background-color: #f5f5f5;
padding: 10px; padding: 10px;
border-radius: 4px; border-radius: 4px;
overflow-x: auto; overflow-x: auto;
} }
button { button {
padding: 8px 16px; padding: 8px 16px;
background-color: #4CAF50; background-color: #4CAF50;
...@@ -39,11 +44,13 @@ ...@@ -39,11 +44,13 @@
margin-right: 10px; margin-right: 10px;
margin-bottom: 10px; margin-bottom: 10px;
} }
button:hover { button:hover {
background-color: #45a049; background-color: #45a049;
} }
</style> </style>
</head> </head>
<body> <body>
<h1>白名单URL简单测试</h1> <h1>白名单URL简单测试</h1>
...@@ -60,7 +67,7 @@ ...@@ -60,7 +67,7 @@
<script> <script>
// 等待页面加载完成 // 等待页面加载完成
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
// 获取DOM元素 // 获取DOM元素
const resultElement = document.getElementById('result'); const resultElement = document.getElementById('result');
const testWhitelistButton = document.getElementById('testWhitelist'); const testWhitelistButton = document.getElementById('testWhitelist');
...@@ -99,18 +106,18 @@ ...@@ -99,18 +106,18 @@
}); });
// 测试白名单内请求 // 测试白名单内请求
testWhitelistButton.addEventListener('click', async function() { testWhitelistButton.addEventListener('click', async function () {
resultElement.textContent = '请求中...'; resultElement.textContent = '请求中...';
try { try {
// 白名单URL列表由SDK内部处理 // 白名单URL列表由SDK内部处理
// 我们只需要在请求参数中添加method参数 // 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数'); console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');
const result = await request.post('/dict/sign/test1', { // 使用params包裹GET请求参数
params: { const result = await request.get('/dict/sign/test', {
id:10, params:{
objs:[1,2,3] id: 10,
// method: 'clue.api.collision.info.exportCollisionInfo' // 白名单内的method "objs":["cc","dd","sss"] // 白名单[内的method
} }
}); });
...@@ -122,19 +129,16 @@ ...@@ -122,19 +129,16 @@
}); });
// 测试白名单外请求 // 测试白名单外请求
testNonWhitelistButton.addEventListener('click', async function() { testNonWhitelistButton.addEventListener('click', async function () {
resultElement.textContent = '请求中...'; resultElement.textContent = '请求中...';
try { try {
// 白名单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.get('/posts/1', { id: 10,
params: { "objs":["cc","dd","sss"] // 白名单[外的method
method: 'user.delete.account' // 白名单外的method
}
}); });
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) {
...@@ -144,4 +148,5 @@ ...@@ -144,4 +148,5 @@
}); });
</script> </script>
</body> </body>
</html> </html>
\ No newline at end of file \ No newline at end of file
...@@ -78,29 +78,36 @@ ...@@ -78,29 +78,36 @@
<script> <script>
// 使用全局变量 // 使用全局变量
const Request = window.glskFetch.default; const Request = window.GlskFetch.default;
const Trace = window.glskFetch.Trace;
// 创建模拟的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({ const request = new Request({
baseURL: 'https://jsonplaceholder.typicode.com', baseURL: 'https://jsonplaceholder.typicode.com',
appId: 'test-app-id', appId: 'test-app-id',
appSecret: 'test-app-secret', appSecret: 'test-app-secret',
timeout: 10000 timeout: 10000,
sentryDsn: 'https://example@sentry.io/123456', // 提供一个示例Sentry DSN
disableSentry: true // 禁用Sentry,避免实际发送错误报告
}); });
// 模拟白名单URL // 模拟白名单URL已在Trace对象中定义
const mockWhitelistUrls = [
'user.get.info',
'order.create',
'product.list'
];
// 覆盖Trace.getTraceUrls方法,返回模拟的白名单URL
Trace.getTraceUrls = async function(forceRefresh = false) {
console.log('获取白名单URL列表');
return mockWhitelistUrls;
};
// 显示当前白名单 // 显示当前白名单
async function displayWhitelist() { async function displayWhitelist() {
...@@ -126,9 +133,7 @@ ...@@ -126,9 +133,7 @@
document.getElementById('testInWhitelist').addEventListener('click', async () => { document.getElementById('testInWhitelist').addEventListener('click', async () => {
try { try {
const result = await request.get('/posts/1', { const result = await request.get('/posts/1', {
params: {
method: 'user.get.info' // 白名单内的method method: 'user.get.info' // 白名单内的method
}
}); });
document.getElementById('result').textContent = document.getElementById('result').textContent =
...@@ -142,9 +147,7 @@ ...@@ -142,9 +147,7 @@
document.getElementById('testNotInWhitelist').addEventListener('click', async () => { document.getElementById('testNotInWhitelist').addEventListener('click', async () => {
try { try {
const result = await request.get('/posts/1', { const result = await request.get('/posts/1', {
params: {
method: 'user.delete.account' // 白名单外的method method: 'user.delete.account' // 白名单外的method
}
}); });
document.getElementById('result').textContent = document.getElementById('result').textContent =
......
...@@ -33,12 +33,33 @@ class WebAdapter extends BaseAdapter { ...@@ -33,12 +33,33 @@ class WebAdapter extends BaseAdapter {
data instanceof Blob || data instanceof Blob ||
data instanceof ArrayBuffer) { data instanceof ArrayBuffer) {
options.body = data; options.body = data;
} else if (typeof data === 'object') { } else if (typeof data === 'object' && data !== null) {
// 检查Content-Type
const contentType = headers['Content-Type'] || '';
// 如果指定了application/x-www-form-urlencoded,转换为表单数据
if (contentType.includes('application/x-www-form-urlencoded')) {
const formData = new URLSearchParams();
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
// 处理数组参数,使用索引格式 key[0]=value, key[1]=value
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, String(item));
});
} else {
formData.append(key, String(value));
}
});
options.body = formData;
} else {
// 默认使用JSON格式
options.body = JSON.stringify(data); options.body = JSON.stringify(data);
console.log("🚀 ~ WebAdapter ~ createRequestOptions ~ options.body:", options.body)
// 设置Content-Type为application/json // 设置Content-Type为application/json
if (!headers['Content-Type']) { if (!headers['Content-Type']) {
(options.headers as Record<string, string>)['Content-Type'] = 'application/json'; (options.headers as Record<string, string>)['Content-Type'] = 'application/json';
} }
}
} else if (data !== undefined) { } else if (data !== undefined) {
options.body = String(data); options.body = String(data);
} }
......
...@@ -82,6 +82,8 @@ class Request { ...@@ -82,6 +82,8 @@ class Request {
request<T = any>( request<T = any>(
options: RequestConfig = {} options: RequestConfig = {}
): Promise<ResponseData<T>> & { abort?: () => void } { ): Promise<ResponseData<T>> & { abort?: () => void } {
console.log("🚀 ~ Request ~ request ~ options:", options)
// 合并配置 // 合并配置
const config = this.defaults.merge(options); const config = this.defaults.merge(options);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!