Commit 16623cf4 by liimin

feat: 添加多环境适配器和请求签名功能

重构请求库以支持Web、小程序和uniapp环境
添加请求签名功能和安全相关工具类
实现数组参数处理和自定义签名函数
更新README文档和示例页面
1 parent eaf9d6a4
...@@ -8,8 +8,10 @@ ...@@ -8,8 +8,10 @@
- 🔐 自动签名:内置签名算法,确保请求安全 - 🔐 自动签名:内置签名算法,确保请求安全
- 🔄 拦截器:支持请求和响应拦截器 - 🔄 拦截器:支持请求和响应拦截器
- ⏱️ 超时控制:可配置请求超时时间 - ⏱️ 超时控制:可配置请求超时时间
- 🚫 请求取消:支持使用 AbortController 取消请求 - 🚫 请求取消:支持使用 AbortController 可取消请求
- 📦 轻量级:无其他依赖,体积小巧 - 📦 轻量级:无其他依赖,体积小巧
- 🔧 可扩展:支持自定义签名算法
- 📋 数组参数:支持发送包含数组的请求参数
## 安装 ## 安装
...@@ -96,6 +98,63 @@ request.interceptors.response.use( ...@@ -96,6 +98,63 @@ request.interceptors.response.use(
); );
``` ```
### 数组参数处理
glsk-fetch 支持发送包含数组的请求参数:
```javascript
// GET 请求中使用数组参数(查询参数)
request.get('/posts', {
params: {
userId: [1, 2, 3] // 默认转换为 userId=1&userId=2&userId=3
}
}).then(response => {
console.log(response.data);
});
// POST 请求中使用数组参数(请求体)
request.post('/posts', {
title: '我的帖子',
body: '帖子内容',
userId: 1,
tags: ['JavaScript', 'TypeScript', 'Fetch'] // 数组会被自动转换为 JSON
}).then(response => {
console.log(response.data);
});
```
### 自定义签名函数
glsk-fetch 支持自定义签名函数,允许用户实现自己的签名算法:
```javascript
// 导入默认签名函数(可选)
import { generateSignature } from 'glsk-fetch';
// 自定义签名函数示例
const customSignatureFunc = ({ appId, appSecret, params }) => {
// 用户自定义的签名算法
const nonce = 'custom-nonce';
const timestamp = Date.now().toString();
// 实现自定义签名逻辑
const sign = 'custom-signature';
return { nonce, timestamp, sign };
};
// 使用自定义签名函数
const request = new Request({
baseURL: 'https://api.example.com',
appId: 'your_app_id',
appSecret: 'your_app_secret',
signatureFunc: customSignatureFunc // 使用自定义签名函数
});
// 发起请求
request.get('/users').then(response => {
console.log(response.data);
});
```
### 取消请求(简化版) ### 取消请求(简化版)
glsk-fetch 现在支持简化版的请求取消方式,请求方法直接返回带有 `abort()` 方法的对象: glsk-fetch 现在支持简化版的请求取消方式,请求方法直接返回带有 `abort()` 方法的对象:
...@@ -209,7 +268,8 @@ const request = new Request({ ...@@ -209,7 +268,8 @@ const request = new Request({
timeout: 5000, // 超时时间(毫秒) timeout: 5000, // 超时时间(毫秒)
appId: '', // 应用ID(用于签名) appId: '', // 应用ID(用于签名)
appSecret: '', // 应用密钥(用于签名) appSecret: '', // 应用密钥(用于签名)
headers: {} // 默认请求头 headers: {}, // 默认请求头
signatureFunc: null // 自定义签名函数
}); });
``` ```
...@@ -237,10 +297,31 @@ const request = new Request({ ...@@ -237,10 +297,31 @@ const request = new Request({
timeout: 5000, // 超时时间 timeout: 5000, // 超时时间
appId: '', // 应用ID appId: '', // 应用ID
appSecret: '', // 应用密钥 appSecret: '', // 应用密钥
signal: AbortSignal // 用于取消请求的信号 signal: AbortSignal, // 用于取消请求的信号
signatureFunc: Function // 自定义签名函数
} }
``` ```
### 签名函数接口
自定义签名函数需要符合以下接口:
```typescript
interface SignatureOptions {
appId: string;
appSecret: string;
params?: Record<string, any>;
}
interface SignatureResult {
nonce: string;
timestamp: string;
sign: string;
}
function signatureFunc(options: SignatureOptions): SignatureResult;
```
## License ## License
MIT MIT
\ No newline at end of file \ No newline at end of file
import type { RequestConfig } from '../types';
import type { Adapter } from './types';
import webAdapter from './web';
import miniprogramAdapter from './miniprogram';
import uniappAdapter from './uniapp';
// 重新导出签名相关功能
export { generateSignature, type SignatureOptions, type SignatureResult } from '../signature';
/**
* 获取适合当前环境的适配器
* @returns {Adapter} 适配器函数
*/
export function getAdapter(): Adapter {
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
// 小程序环境
return miniprogramAdapter;
} else if (typeof uni !== 'undefined' && uni && 'request' in uni) {
// uniapp环境
return uniappAdapter;
} else {
// Web环境
return webAdapter;
}
}
// 导出所有适配器
export {
webAdapter,
miniprogramAdapter,
uniappAdapter
};
// 导出适配器相关类型
export * from './types';
\ No newline at end of file \ No newline at end of file
import { RequestError } from '../error';
import type { RequestConfig, ResponseData } from '../types';
import { buildURL } from './utils';
import type { Adapter, MiniProgramRequestOptions } from './types';
/**
* 小程序环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
const miniprogramAdapter: Adapter = function(config: RequestConfig): Promise<ResponseData<any>> {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000,
signal
} = config;
// 创建请求Promise
const requestPromise = new Promise<ResponseData<any>>((resolve, reject) => {
// 构建完整URL
const fullURL = buildURL(baseURL, url, params, method);
// 小程序请求选项
const requestOption: MiniProgramRequestOptions = {
url: fullURL,
method: method.toUpperCase(),
header: headers,
timeout,
success: (res) => {
// 检查状态码
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve({
data: res.data,
status: res.statusCode,
statusText: res.errMsg,
headers: res.header,
config
});
} else {
reject(RequestError.createServerError(
`请求失败: ${res.statusCode}`,
config,
null,
{
data: res.data,
status: res.statusCode,
statusText: res.errMsg,
headers: res.header,
config
}
));
}
},
fail: (err) => {
// 处理不同类型的错误
if (err.errMsg && err.errMsg.includes('timeout')) {
reject(RequestError.createTimeoutError(config));
} else if (err.errMsg && err.errMsg.includes('abort')) {
reject(RequestError.createCancelError(config));
} else {
reject(RequestError.createNetworkError(err.errMsg || '请求失败', config));
}
}
};
// 处理请求体
if (method.toUpperCase() !== 'GET') {
requestOption.data = data;
}
// 发起请求
let requestTask: any;
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
requestTask = wx.request(requestOption);
// 如果存在signal,监听abort事件
if (signal) {
const abortHandler = () => {
if (requestTask && typeof requestTask.abort === 'function') {
requestTask.abort();
}
reject(RequestError.createCancelError(config));
};
// 如果已经被取消,直接执行abort
if (signal.aborted) {
abortHandler();
} else {
signal.addEventListener('abort', abortHandler);
}
}
} else {
reject(RequestError.createRequestError('当前环境不支持小程序请求', config, 'ENVIRONMENT_ERROR'));
}
});
// 创建超时Promise
const timeoutPromise = new Promise<never>((_, reject) => {
if (timeout) {
setTimeout(() => {
reject(RequestError.createTimeoutError(config));
}, timeout);
}
});
// 使用Promise.race竞争超时和请求
return Promise.race([requestPromise, timeoutPromise]);
};
export default miniprogramAdapter;
\ No newline at end of file \ No newline at end of file
import type { RequestConfig, ResponseData } from '../types';
// 小程序请求选项接口
export interface MiniProgramRequestOptions {
url: string;
method: string;
header?: RequestConfig['headers'];
timeout?: number;
data?: any;
success: (res: any) => void;
fail: (err: any) => void;
}
// uniapp请求选项接口
export interface UniAppRequestOptions {
url: string;
method: string;
header?: RequestConfig['headers'];
timeout?: number;
data?: any;
success: (res: any) => void;
fail: (err: any) => void;
}
// 小程序接口
export interface MiniProgram {
request: (options: MiniProgramRequestOptions) => void;
}
// uniapp接口
export interface UniApp {
request: (options: UniAppRequestOptions) => void;
}
// 声明全局变量
declare global {
const wx: MiniProgram | undefined;
const uni: UniApp | undefined;
}
// 适配器接口
export type Adapter = (config: RequestConfig) => Promise<ResponseData<any>>;
\ No newline at end of file \ No newline at end of file
import { RequestError } from '../error';
import type { RequestConfig, ResponseData } from '../types';
import { buildURL } from './utils';
import type { Adapter, UniAppRequestOptions } from './types';
/**
* uniapp环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
const uniappAdapter: Adapter = function(config: RequestConfig): Promise<ResponseData<any>> {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000,
signal
} = config;
// 创建请求Promise
const requestPromise = new Promise<ResponseData<any>>((resolve, reject) => {
// 构建完整URL
const fullURL = buildURL(baseURL, url, params, method);
// uniapp请求选项
const requestOption: UniAppRequestOptions = {
url: fullURL,
method: method.toUpperCase(),
header: headers,
timeout,
success: (res) => {
// 检查状态码
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve({
data: res.data,
status: res.statusCode,
statusText: res.errMsg,
headers: res.header,
config
});
} else {
reject(RequestError.createServerError(
`请求失败: ${res.statusCode}`,
config,
null,
{
data: res.data,
status: res.statusCode,
statusText: res.errMsg,
headers: res.header,
config
}
));
}
},
fail: (err) => {
// 处理不同类型的错误
if (err.errMsg && err.errMsg.includes('timeout')) {
reject(RequestError.createTimeoutError(config));
} else if (err.errMsg && err.errMsg.includes('abort')) {
reject(RequestError.createCancelError(config));
} else {
reject(RequestError.createNetworkError(err.errMsg || '请求失败', config));
}
}
};
// 处理请求体
if (method.toUpperCase() !== 'GET') {
requestOption.data = data;
}
// 发起请求
let requestTask: any;
if (typeof uni !== 'undefined' && uni && 'request' in uni) {
requestTask = uni.request(requestOption);
// 如果存在signal,监听abort事件
if (signal) {
const abortHandler = () => {
if (requestTask && typeof requestTask.abort === 'function') {
requestTask.abort();
}
reject(RequestError.createCancelError(config));
};
// 如果已经被取消,直接执行abort
if (signal.aborted) {
abortHandler();
} else {
signal.addEventListener('abort', abortHandler);
}
}
} else {
reject(RequestError.createRequestError('当前环境不支持uniapp请求', config, 'ENVIRONMENT_ERROR'));
}
});
// 创建超时Promise
const timeoutPromise = new Promise<never>((_, reject) => {
if (timeout) {
setTimeout(() => {
reject(RequestError.createTimeoutError(config));
}, timeout);
}
});
// 使用Promise.race竞争超时和请求
return Promise.race([requestPromise, timeoutPromise]);
};
export default uniappAdapter;
\ No newline at end of file \ No newline at end of file
import type { RequestConfig } from '../types';
/**
* 构建完整URL
* @param {string} baseURL 基础URL
* @param {string} url 请求路径
* @param {Record<string, any>} params 查询参数
* @param {string} method 请求方法
* @returns {string} 完整URL
*/
export function buildURL(baseURL: string = '', url: string = '', params: Record<string, any> = {}, method: string = 'GET'): string {
// 构建基础URL
let fullURL = baseURL + url;
// 处理GET请求参数或其他方法的URL参数
if ((method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') && Object.keys(params).length) {
const queryParts: string[] = [];
// 遍历所有参数
Object.keys(params).forEach(key => {
const value = params[key];
// 处理数组参数
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('&');
fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
}
return fullURL;
}
/**
* 解析响应头
* @param {Headers} headers 响应头
* @returns {Record<string, string>} 解析后的响应头对象
*/
export function parseHeaders(headers: Headers): Record<string, string> {
const result: Record<string, string> = {};
headers.forEach((value, key) => {
result[key] = value;
});
return result;
}
\ No newline at end of file \ No newline at end of file
import { RequestError } from '../error';
import type { RequestConfig, ResponseData } from '../types';
import { buildURL, parseHeaders } from './utils';
import type { Adapter } from './types';
/**
* Web环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
const webAdapter: Adapter = function(config: RequestConfig): Promise<ResponseData<any>> {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000,
signal
} = config;
// 构建完整URL
const fullURL = buildURL(baseURL, url, params, method);
// 创建fetch选项
const fetchOptions: RequestInit & { timeout?: number } = {
method: method.toUpperCase(),
headers: headers as HeadersInit,
timeout
};
// 处理请求体
if (method.toUpperCase() !== 'GET' && Object.keys(data).length) {
if (headers['Content-Type'] && headers['Content-Type'].includes('application/json')) {
fetchOptions.body = JSON.stringify(data);
} else {
fetchOptions.body = data as BodyInit;
}
}
// 设置signal
if (signal) {
fetchOptions.signal = signal;
}
// 设置超时
let timeoutId: NodeJS.Timeout | null = null;
const timeoutPromise = new Promise<never>((_, reject) => {
if (timeout && !signal?.aborted) {
timeoutId = setTimeout(() => {
// 创建超时错误
const timeoutError = RequestError.createTimeoutError(config);
reject(timeoutError);
// 同时取消请求
// 注意:我们不能直接调用controller.abort(),因为controller在此作用域不可见
// 但我们可以通过创建一个新的AbortError来模拟请求被取消
// 实际上,当超时发生时,我们已经通过reject抛出了超时错误,这里不需要额外操作
}, timeout);
}
});
// 创建fetch请求Promise
const fetchPromise: Promise<ResponseData<any>> = fetch(fullURL, fetchOptions)
.then(response => {
// 请求成功,清除超时定时器
if (timeoutId) clearTimeout(timeoutId);
// 检查HTTP状态码
if (!response.ok) {
throw RequestError.createServerError(
`请求失败: ${response.status} ${response.statusText}`,
config,
null,
{
status: response.status,
statusText: response.statusText,
headers: parseHeaders(response.headers),
config
}
);
}
return response.json().catch(() => response.text());
})
.then(data => ({
data,
status: 200,
statusText: 'OK',
headers: {},
config
}));
// 使用Promise.race竞争超时和请求
return Promise.race([fetchPromise, timeoutPromise])
.catch(error => {
// 无论哪种情况都清除超时定时器
if (timeoutId) clearTimeout(timeoutId);
// 已经是RequestError类型的错误直接抛出
if (error.isRequestError) {
throw error;
}
// 处理取消请求的情况
if (error.name === 'AbortError' || (signal && signal.aborted)) {
throw RequestError.createCancelError(config);
}
// 处理网络错误
if (error.message && error.message.includes('NetworkError')) {
throw RequestError.createNetworkError(error.message, config);
}
// 其他未知错误
throw RequestError.createRequestError(error.message || '请求失败', config);
});
};
export default webAdapter;
\ No newline at end of file \ No newline at end of file
/**
* 请求错误类
*/
export class RequestError extends Error {
code: string;
config: any;
request?: any;
response?: any;
isRequestError: boolean;
constructor(message: string, code: string, config: any, request?: any, response?: any) {
super(message);
this.name = 'RequestError';
this.code = code;
this.config = config;
this.request = request;
this.response = response;
this.isRequestError = true;
// 确保instanceof正常工作
Object.setPrototypeOf(this, RequestError.prototype);
}
/**
* 创建网络错误
*/
static createNetworkError(message: string, config: any, request?: any): RequestError {
return new RequestError(
message || '网络错误',
'NETWORK_ERROR',
config,
request
);
}
/**
* 创建超时错误
*/
static createTimeoutError(config: any, request?: any): RequestError {
return new RequestError(
`请求超时: 超过了${config.timeout}ms`,
'TIMEOUT_ERROR',
config,
request
);
}
/**
* 创建取消错误
*/
static createCancelError(config: any, request?: any): RequestError {
return new RequestError(
'请求已被取消',
'CANCEL_ERROR',
config,
request
);
}
/**
* 创建服务器错误
*/
static createServerError(message: string, config: any, request?: any, response?: any): RequestError {
return new RequestError(
message || '服务器错误',
'SERVER_ERROR',
config,
request,
response
);
}
/**
* 创建请求错误
*/
static createRequestError(message: string, config: any, code = 'REQUEST_ERROR', request?: any): RequestError {
return new RequestError(
message,
code,
config,
request
);
}
}
\ No newline at end of file \ No newline at end of file
import Request from './request'; import Request from './request';
import { RequestError } from './error';
import { generateSignature, type SignatureOptions, type SignatureResult } from './signature';
// 导出错误类和签名功能
// export { RequestError, generateSignature, type SignatureOptions, type SignatureResult };
export default Request; export default Request;
\ No newline at end of file \ No newline at end of file
import type { InterceptorHandler } from './types'; import type { InterceptorHandler, RequestError } from './types';
class InterceptorManager { class InterceptorManager<T = any> {
private handlers: (InterceptorHandler | null)[] = []; private handlers: (InterceptorHandler<T> | null)[] = [];
/** /**
* 添加拦截器 * 添加拦截器
...@@ -10,8 +10,8 @@ class InterceptorManager { ...@@ -10,8 +10,8 @@ class InterceptorManager {
* @returns {Function} 移除拦截器的函数 * @returns {Function} 移除拦截器的函数
*/ */
use( use(
fulfilled: (value: any) => any | Promise<any>, fulfilled: (value: T) => T | Promise<T>,
rejected?: (error: any) => any rejected?: (error: RequestError) => any
): number { ): number {
const id = this.handlers.push({ const id = this.handlers.push({
fulfilled, fulfilled,
...@@ -26,7 +26,7 @@ class InterceptorManager { ...@@ -26,7 +26,7 @@ class InterceptorManager {
* 遍历执行拦截器 * 遍历执行拦截器
* @param {Function} fn 执行函数 * @param {Function} fn 执行函数
*/ */
forEach(fn: (handler: InterceptorHandler) => void): void { forEach(fn: (handler: InterceptorHandler<T>) => void): void {
this.handlers.forEach(handler => { this.handlers.forEach(handler => {
if (handler !== null) { if (handler !== null) {
fn(handler); fn(handler);
......
...@@ -7,7 +7,22 @@ export interface RequestHeaders { ...@@ -7,7 +7,22 @@ export interface RequestHeaders {
[key: string]: string | undefined; [key: string]: string | undefined;
} }
export interface RequestConfig { export interface RequestError extends Error {
code: string;
config: RequestConfig;
request?: any;
response?: ResponseData;
isRequestError: boolean;
}
export interface RetryConfig {
retries?: number; // 最大重试次数
retryDelay?: number; // 重试延迟时间(ms)
retryCondition?: (error: RequestError) => boolean; // 重试条件
shouldResetTimeout?: boolean; // 重试时是否重置超时计时器
}
export interface RequestConfig extends RetryConfig {
url?: string; url?: string;
method?: string; method?: string;
baseURL?: string; baseURL?: string;
...@@ -17,39 +32,53 @@ export interface RequestConfig { ...@@ -17,39 +32,53 @@ export interface RequestConfig {
timeout?: number; timeout?: number;
appId?: string; appId?: string;
appSecret?: string; appSecret?: string;
signal?: AbortSignal; // 添加signal属性支持请求取消 signal?: AbortSignal;
signatureFunc?: (options: SignatureOptions) => SignatureResult; // 添加自定义签名函数
}
export interface SignatureOptions {
appId: string;
appSecret: string;
params?: Record<string, any>;
}
export interface SignatureResult {
nonce: string;
timestamp: string;
sign: string;
} }
export interface ResponseData { export interface ResponseData<T = any> {
data: any; data: T;
status: number; status: number;
statusText: string; statusText: string;
headers: Record<string, any>; headers: Record<string, string>;
config: RequestConfig; config: RequestConfig;
} }
export interface InterceptorHandler { export interface InterceptorHandler<T = any> {
fulfilled: (value: any) => any | Promise<any>; fulfilled: (value: T) => T | Promise<T>;
rejected: (error: any) => any; rejected: (error: RequestError) => any;
} }
export interface InterceptorManagerInstance { export interface InterceptorManagerInstance<T = any> {
use(fulfilled: (value: any) => any | Promise<any>, rejected?: (error: any) => any): number; use(fulfilled: (value: T) => T | Promise<T>, rejected?: (error: RequestError) => any): number;
eject(id: number): void; eject(id: number): void;
forEach(fn: (handler: InterceptorHandler<T>) => void): void;
} }
export interface RequestInstance { export interface RequestInstance {
defaults: RequestConfig; defaults: RequestConfig;
interceptors: { interceptors: {
request: InterceptorManagerInstance; request: InterceptorManagerInstance<RequestConfig>;
response: InterceptorManagerInstance; response: InterceptorManagerInstance<ResponseData>;
}; };
request(config?: RequestConfig): Promise<any>; request<T = any>(config?: RequestConfig): Promise<ResponseData<T>> & { abort?: () => void };
get(url: string, config?: RequestConfig): Promise<any>; get<T = any>(url: string, config?: RequestConfig): Promise<ResponseData<T>>;
delete(url: string, config?: RequestConfig): Promise<any>; delete<T = any>(url: string, config?: RequestConfig): Promise<ResponseData<T>>;
head(url: string, config?: RequestConfig): Promise<any>; head<T = any>(url: string, config?: RequestConfig): Promise<ResponseData<T>>;
options(url: string, config?: RequestConfig): Promise<any>; options<T = any>(url: string, config?: RequestConfig): Promise<ResponseData<T>>;
post(url: string, data?: any, config?: RequestConfig): Promise<any>; post<T = any>(url: string, data?: any, config?: RequestConfig): Promise<ResponseData<T>>;
put(url: string, data?: any, config?: RequestConfig): Promise<any>; put<T = any>(url: string, data?: any, config?: RequestConfig): Promise<ResponseData<T>>;
patch(url: string, data?: any, config?: RequestConfig): Promise<any>; patch<T = any>(url: string, data?: any, config?: RequestConfig): Promise<ResponseData<T>>;
} }
\ 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>GET请求参数测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.result {
margin-top: 10px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
white-space: pre-wrap;
}
button {
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>GET请求参数测试</h1>
<div>
<h2>普通参数测试</h2>
<button id="normalParamsTest">测试普通参数</button>
<div id="normalParamsResult" class="result"></div>
</div>
<div>
<h2>数组参数测试</h2>
<button id="arrayParamsTest">测试数组参数</button>
<div id="arrayParamsResult" class="result"></div>
</div>
<script src="./dist/index.umd.js"></script>
<script>
// 创建请求实例
const request = new Request({
baseURL: 'https://httpbin.org',
timeout: 5000,
appId: 'test_app_id',
appSecret: 'test_app_secret'
});
// 显示结果函数
function showResult(elementId, data) {
const resultElement = document.getElementById(elementId);
resultElement.textContent = JSON.stringify(data, null, 2);
}
// 测试普通参数
document.getElementById('normalParamsTest').addEventListener('click', () => {
const resultElement = document.getElementById('normalParamsResult');
resultElement.textContent = '请求中...';
console.log('发送普通参数请求');
request.get('/get', {
params: {
name: '张三',
age: 25,
active: true
}
})
.then(response => {
console.log('普通参数请求响应:', response);
console.log('请求URL:', response.config.url);
console.log('请求参数:', response.config.params);
console.log('响应参数:', response.data.args);
showResult('normalParamsResult', {
url: response.config.url, // 显示完整URL
params: response.config.params, // 显示参数对象
args: response.data.args // httpbin返回的解析后的参数
});
})
.catch(error => {
console.error('普通参数请求失败:', error);
resultElement.textContent = `请求失败: ${error.message}`;
});
});
// 测试数组参数
document.getElementById('arrayParamsTest').addEventListener('click', () => {
const resultElement = document.getElementById('arrayParamsResult');
resultElement.textContent = '请求中...';
console.log('发送数组参数请求');
request.get('/get', {
params: {
id: [1, 2, 3],
tags: ['javascript', 'typescript', 'fetch']
}
})
.then(response => {
console.log('数组参数请求响应:', response);
console.log('请求URL:', response.config.url);
console.log('请求参数:', response.config.params);
console.log('响应参数:', response.data.args);
showResult('arrayParamsResult', {
url: response.config.url, // 显示完整URL
params: response.config.params, // 显示参数对象
args: response.data.args // httpbin返回的解析后的参数
});
})
.catch(error => {
console.error('数组参数请求失败:', error);
resultElement.textContent = `请求失败: ${error.message}`;
});
});
</script>
</body>
</html>
\ 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!