Commit 6ad60020 by liimin

feat: 新增simpleGet函数并导出响应处理器相关功能

新增simpleGet函数用于简化GET请求,同时导出响应处理器相关功能(processResponse, addEventListener, removeEventListener)
更新示例和文档,添加simpleGet测试页面和响应处理器测试页面
修改whitelist-simple-test.html示例中的配置和接口地址
1 parent 921cdc8d
...@@ -48,7 +48,36 @@ request.post('/users', { ...@@ -48,7 +48,36 @@ request.post('/users', {
}); });
``` ```
### 使用 async/await ### 简单GET请求(simpleGet)
如果只需要发送简单的GET请求而不需要签名和其他复杂配置,可以使用导出的`simpleGet`函数:
```javascript
import { simpleGet } from 'glsk-fetch';
// 发送简单的GET请求
simpleGet('https://api.example.com/data')
.then(response => {
console.log(response);
})
.catch(error => {
console.error('请求失败:', error);
});
// 使用async/await
async function fetchData() {
try {
const data = await simpleGet('https://jsonplaceholder.typicode.com/posts/1');
console.log('获取到的数据:', data);
} catch (error) {
console.error('请求失败:', error);
}
}
```
**注意:** `simpleGet`函数是一个轻量级的GET请求工具,不包含签名、拦截器等高级功能。如果需要这些功能,请使用完整的Request类。
### 使用 Defaults 类async/await
```javascript ```javascript
import Request from 'glsk-fetch'; import Request from 'glsk-fetch';
...@@ -285,6 +314,181 @@ request.get('/users', { ...@@ -285,6 +314,181 @@ request.get('/users', {
controller.abort(); controller.abort();
``` ```
### 响应处理器外部配置
glsk-fetch 支持通过外部配置来自定义响应数据的处理逻辑,包括状态码字段映射、数据字段提取和事件触发机制。
#### 基本配置
```javascript
import Request from 'glsk-fetch';
// 配置响应处理器
Request.defaults.httpOptions = {
customer: {
response: {
code_key: "status", // 状态码字段名
code_success_value: "200", // 成功状态码值
data_key: "result", // 数据字段名
errId: "errorId", // 错误ID字段名
errId_logout_value: "401" // 登出状态码值
}
}
};
// 发起请求
Request.get('/api/data').then(response => {
// 响应会根据配置自动处理
console.log(response);
});
```
#### 数组形式的状态码字段
支持使用数组形式的 `code_key`,系统会自动匹配响应中存在的字段:
```javascript
Request.defaults.httpOptions = {
customer: {
response: {
code_key: ["code", "status", "errorCode"], // 自动匹配存在的字段
code_success_value: "0",
data_key: "data"
}
}
};
```
#### returnAll 模式
当设置 `returnAll: true` 时,返回完整的响应数据而不仅仅是 `data_key` 指定的字段:
```javascript
Request.get('/api/data', {
returnAll: true,
httpOptions: {
customer: {
response: {
code_key: "status",
data_key: "payload"
}
}
}
}).then(response => {
// 返回完整响应数据
console.log(response);
});
```
#### 配置选项说明
| 选项 | 类型 | 默认值 | 说明 |
|------|------|--------|---------|
| `code_key` | `string \| string[]` | - | 状态码字段名,支持数组形式自动匹配 |
| `code_success_value` | `string \| number` | `"0"` | 表示成功的状态码值 |
| `data_key` | `string` | `"data"` | 数据字段名 |
| `errId` | `string` | `"errId"` | 错误ID字段名 |
| `errId_logout_value` | `string \| number` | - | 表示需要登出的状态码值 |
| `returnAll` | `boolean` | `false` | 是否返回完整响应数据 |
### 事件监听器
glsk-fetch 提供了强大的事件系统,允许你监听请求和响应的各个阶段,实现全局的状态管理和错误处理。
#### 基本使用
```javascript
import Request, { addEventListener, removeEventListener } from 'glsk-fetch';
// 监听成功事件
const unsubscribeSuccess = addEventListener('success', (data, config) => {
console.log('请求成功:', data);
console.log('请求配置:', config);
});
// 监听错误事件
const unsubscribeError = addEventListener('error', (data, config) => {
console.error('请求失败:', data);
// 可以在这里显示全局错误提示
});
// 监听登出事件
const unsubscribeLogout = addEventListener('logout', (data, config) => {
console.log('用户需要重新登录');
// 可以在这里跳转到登录页面
window.location.href = '/login';
});
// 监听所有响应事件
const unsubscribeResponse = addEventListener('response', (responseData, config) => {
console.log('收到响应:', responseData);
// 可以在这里进行全局的响应处理
});
// 取消监听
// unsubscribeSuccess();
// unsubscribeError();
```
#### 事件类型
| 事件类型 | 触发时机 | 参数说明 |
|----------|----------|----------|
| `success` | 响应状态码匹配 `code_success_value` 时 | `(data, config)` - 响应数据和请求配置 |
| `error` | 响应状态码不匹配成功值且不是登出状态时 | `(data, config)` - 响应数据和请求配置 |
| `logout` | 响应状态码匹配 `errId_logout_value` 时 | `(data, config)` - 响应数据和请求配置 |
| `response` | 收到任何响应时(无论成功或失败) | `(responseData, config)` - 完整响应数据和请求配置 |
#### 实际应用示例
```javascript
import Request, { addEventListener } from 'glsk-fetch';
// 全局错误处理
addEventListener('error', (data, config) => {
// 显示错误提示
if (data.message) {
alert(`请求失败: ${data.message}`);
}
// 记录错误日志
console.error('API Error:', {
url: config.url,
method: config.method,
error: data
});
});
// 全局登出处理
addEventListener('logout', (data, config) => {
// 清除本地存储的用户信息
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
// 跳转到登录页面
window.location.href = '/login';
});
// 全局成功处理
addEventListener('success', (data, config) => {
// 可以在这里进行一些全局的成功处理
console.log('操作成功:', data);
});
// 配置响应处理器
Request.defaults.httpOptions = {
customer: {
response: {
code_key: "code",
code_success_value: "200",
data_key: "data",
errId: "errId",
errId_logout_value: "401"
}
}
};
```
### 批量请求的选择性取消 ### 批量请求的选择性取消
```javascript ```javascript
...@@ -422,6 +626,19 @@ const request = new Request({ ...@@ -422,6 +626,19 @@ const request = new Request({
appSecret: '', // 应用密钥 appSecret: '', // 应用密钥
signal: AbortSignal, // 用于取消请求的信号 signal: AbortSignal, // 用于取消请求的信号
signatureFunc: Function, // 自定义签名函数 signatureFunc: Function, // 自定义签名函数
returnAll: false, // 是否返回完整响应数据
responseType: 'json', // 响应数据类型: 'json' | 'text' | 'blob' | 'arraybuffer'
httpOptions: { // HTTP选项配置
customer: {
response: {
code_key: '', // 状态码字段名,支持字符串或数组
code_success_value: '0', // 成功状态码值
data_key: 'data', // 数据字段名
errId: 'errId', // 错误ID字段名
errId_logout_value: '' // 登出状态码值
}
}
},
sentry: { // Sentry 错误上报配置 sentry: { // Sentry 错误上报配置
enable: false, // 是否启用Sentry错误上报 enable: false, // 是否启用Sentry错误上报
dsn: '', // Sentry DSN dsn: '', // Sentry DSN
...@@ -435,6 +652,33 @@ const request = new Request({ ...@@ -435,6 +652,33 @@ const request = new Request({
} }
``` ```
### 导出函数
除了默认的 Request 实例外,glsk-fetch 还导出了以下函数:
```javascript
import Request, {
addEventListener,
removeEventListener,
processResponse,
Defaults,
Sentry,
simpleGet
} from 'glsk-fetch';
// 事件监听器函数
addEventListener(eventType, handler); // 添加事件监听器
removeEventListener(eventType, handler); // 移除事件监听器
// 响应处理函数
processResponse(responseData, config); // 手动处理响应数据
// 其他工具函数
Defaults; // 默认配置管理
Sentry; // Sentry 错误上报工具
simpleGet; // 简单的 GET 请求函数
```
### 签名函数接口 ### 签名函数接口
自定义签名函数需要符合以下接口: 自定义签名函数需要符合以下接口:
...@@ -455,6 +699,41 @@ interface SignatureResult { ...@@ -455,6 +699,41 @@ interface SignatureResult {
function signatureFunc(options: SignatureOptions): SignatureResult; function signatureFunc(options: SignatureOptions): SignatureResult;
``` ```
## 开发和测试
### 响应处理器测试页面
项目提供了一个完整的测试页面来验证响应处理器的外部配置功能:
```bash
# 启动开发服务器
npm run dev
# 访问测试页面
http://localhost:8080/examples/response-handler-test.html
```
测试页面包含以下功能:
1. **自定义 code_key 配置测试** - 验证自定义状态码字段名的处理
2. **数组形式 code_key 配置测试** - 验证数组形式状态码字段的自动匹配
3. **登出状态码配置测试** - 验证登出状态码的识别和事件触发
4. **returnAll 模式测试** - 验证完整响应数据返回模式
5. **无配置情况测试** - 验证默认行为
6. **事件日志功能** - 实时查看 `success`、`error`、`logout`、`response` 事件的触发情况
每个测试都会显示:
- 配置参数
- 模拟响应数据
- 处理后的结果
- 触发的事件日志
这个测试页面可以帮助开发者:
- 理解响应处理器的工作原理
- 验证自定义配置的正确性
- 调试事件监听器的行为
- 学习最佳实践
## License ## License
MIT MIT
\ 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>simpleGet函数测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.test-section {
background: white;
margin: 20px 0;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.test-section h3 {
color: #333;
margin-top: 0;
}
button {
background: #007cba;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:hover {
background: #005a87;
}
.result {
margin-top: 10px;
padding: 10px;
border-radius: 4px;
background: #f8f9fa;
border-left: 4px solid #007cba;
max-height: 300px;
overflow-y: auto;
}
.error {
border-left-color: #dc3545;
background: #f8d7da;
}
.success {
border-left-color: #28a745;
background: #d4edda;
}
pre {
white-space: pre-wrap;
word-break: break-all;
}
</style>
</head>
<body>
<h1>simpleGet函数测试</h1>
<p>测试从主入口导出的simpleGet函数,用于简单的GET请求</p>
<!-- 测试1:基本GET请求 -->
<div class="test-section">
<h3>测试1:基本GET请求</h3>
<p>使用simpleGet函数发送简单的GET请求</p>
<button onclick="testBasicGet()">测试基本GET请求</button>
<div id="result1" class="result" style="display: none;"></div>
</div>
<!-- 测试2:JSON API请求 -->
<div class="test-section">
<h3>测试2:JSON API请求</h3>
<p>请求JSON格式的API数据</p>
<button onclick="testJsonApi()">测试JSON API</button>
<div id="result2" class="result" style="display: none;"></div>
</div>
<!-- 测试3:错误处理 -->
<div class="test-section">
<h3>测试3:错误处理</h3>
<p>测试无效URL的错误处理</p>
<button onclick="testErrorHandling()">测试错误处理</button>
<div id="result3" class="result" style="display: none;"></div>
</div>
<script type="module">
// 导入 simpleGet 函数
import { simpleGet } from '../dist/index.esm.js';
// 检查函数是否正确导出
if (typeof simpleGet !== 'function') {
console.error('❌ simpleGet函数未正确导出');
alert('❌ simpleGet函数未正确导出');
throw new Error('simpleGet函数未正确导出');
}
console.log('✅ simpleGet函数导出成功,类型:', typeof simpleGet);
// 将函数挂载到全局对象以供其他脚本使用
window.simpleGet = simpleGet;
// 测试1:基本GET请求
window.testBasicGet = async function() {
const resultDiv = document.getElementById('result1');
resultDiv.style.display = 'block';
resultDiv.className = 'result';
resultDiv.innerHTML = '请求中...';
try {
if (!simpleGet) {
throw new Error('simpleGet函数未正确导出');
}
// 测试一个简单的API
const response = await simpleGet('https://httpbin.org/get');
resultDiv.className = 'result success';
resultDiv.innerHTML = `
<strong>✓ 请求成功</strong><br>
<strong>响应数据:</strong><br>
<pre>${JSON.stringify(response, null, 2)}</pre>
`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.innerHTML = `
<strong>✗ 请求失败</strong><br>
错误信息:${error.message}<br>
<pre>${error.stack || ''}</pre>
`;
}
}
// 测试2:JSON API请求
window.testJsonApi = async function() {
const resultDiv = document.getElementById('result2');
resultDiv.style.display = 'block';
resultDiv.className = 'result';
resultDiv.innerHTML = '请求中...';
try {
if (!simpleGet) {
throw new Error('simpleGet函数未正确导出');
}
// 测试JSON API
const response = await simpleGet('https://jsonplaceholder.typicode.com/posts/1');
resultDiv.className = 'result success';
resultDiv.innerHTML = `
<strong>✓ JSON API请求成功</strong><br>
<strong>文章标题:</strong>${response.title}<br>
<strong>文章内容:</strong>${response.body}<br>
<strong>完整响应:</strong><br>
<pre>${JSON.stringify(response, null, 2)}</pre>
`;
} catch (error) {
resultDiv.className = 'result error';
resultDiv.innerHTML = `
<strong>✗ JSON API请求失败</strong><br>
错误信息:${error.message}<br>
<pre>${error.stack || ''}</pre>
`;
}
}
// 测试3:错误处理
window.testErrorHandling = async function() {
const resultDiv = document.getElementById('result3');
resultDiv.style.display = 'block';
resultDiv.className = 'result';
resultDiv.innerHTML = '测试中...';
try {
if (!simpleGet) {
throw new Error('simpleGet函数未正确导出');
}
// 测试无效URL
await simpleGet('');
resultDiv.className = 'result error';
resultDiv.innerHTML = '<strong>✗ 错误处理测试失败</strong><br>应该抛出错误但没有';
} catch (error) {
resultDiv.className = 'result success';
resultDiv.innerHTML = `
<strong>✓ 错误处理正常</strong><br>
正确捕获到错误:${error.message}
`;
}
}
// 页面加载时检查函数是否可用
window.addEventListener('load', function() {
if (simpleGet) {
console.log('✓ simpleGet函数已成功导出并可用');
} else {
console.error('✗ simpleGet函数未正确导出');
}
});
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
...@@ -99,15 +99,15 @@ ...@@ -99,15 +99,15 @@
// 创建请求实例 // 创建请求实例
const request = new RequestConstructor({ const request = new RequestConstructor({
baseURL: 'http://192.168.1.117:9898/facade', baseURL: 'http://192.168.3.145:9898/gsc-vcp-web-facade',
appId: 'dj_zhixin', appId: 'dj_zhixin',
appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b', appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
sentry: { sentry: {
enable: true, enable: false,
dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1' dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1'
}, },
security: { security: {
enable: true, enable: false,
address: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common' // 自定义地址 address: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common' // 自定义地址
} }
}); });
...@@ -121,12 +121,13 @@ ...@@ -121,12 +121,13 @@
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数'); console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');
// 使用params包裹GET请求参数 // 使用params包裹GET请求参数
const result = await request.get('/dict/sign/test', { const result = await request.get('/test/param/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},{"name":"拉布拉多","age":2}],
"dogs":{"name":"haogou","age":1} "dogs":{"name":"haogou","age":1},
"X-Mock":false
} }
}); });
...@@ -143,14 +144,18 @@ ...@@ -143,14 +144,18 @@
try { try {
// 白名单URL列表由SDK内部处理 // 白名单URL列表由SDK内部处理
// 我们只需要在请求参数中添加method参数 // 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数'); console.log('发送请求,SDK将自动检查白名单并添加sdctag参数',request.request);
// POST请求使用data传递参数(放在请求体中) // POST请求使用data传递参数(放在请求体中)
const result = await request.post('/dict/sign/test1', { const result = await request.request( {
url:'/test/param/test',
method:'POST',
data: {
"id": 6, "id": 6,
"objs": ["hehe", "haah"], "objs": ["hehe", "haah"],
"dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}], "dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}],
"dog": {"name": "haogou", "age": 1} "dog": {"name": "haogou", "age": 1}
}
}); });
resultElement.textContent = resultElement.textContent =
......
import Request from './core/request'; import Request from './core/request';
import Defaults from './core/defaults'; import Defaults from './core/defaults';
import * as Sentry from './monitoring/sentry'; import * as Sentry from './monitoring/sentry';
import { simpleGet } from './utils/http';
import { initAbortControllerPolyfill } from './utils/polyfill'; import { initAbortControllerPolyfill } from './utils/polyfill';
import { processResponse, addEventListener, removeEventListener } from './adapter/handlers/response-handler';
// 初始化 AbortController polyfill(如果需要的话) // 初始化 AbortController polyfill(如果需要的话)
initAbortControllerPolyfill(); initAbortControllerPolyfill();
export default Request; export default Request;
export { Defaults, Sentry }; export { Defaults, Sentry, simpleGet, processResponse, addEventListener, removeEventListener };
export type { RequestConfig, ResponseData, RequestHeaders } from './types'; export type { RequestConfig, ResponseData, RequestHeaders } from './types';
export type { SentryOptions, ErrorReportOptions } from './monitoring/sentry'; export type { SentryOptions, ErrorReportOptions } from './monitoring/sentry';
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!