Commit eaf9d6a4 by liimin

docs: 添加项目文档和示例

- 新增 README.md 文件,详细介绍项目功能和使用方法
- 新增 .gitignore 文件,配置项目忽略文件
- 新增 demo.html 文件,展示项目功能和使用示例
0 parents
# Dependencies
node_modules
# Build outputs
dist
# Environment files
.env*
# IDE files
.vscode
.idea
# OS generated files
.DS_Store
Thumbs.db
# Log files
*.log
# Temporary files
*.tmp
*.temp
\ No newline at end of file
# glsk-fetch
一个兼容Web端与小程序端的请求库,带有签名算法和拦截器功能
## 功能特性
- 🌐 跨平台支持:同时支持 Web 浏览器和微信小程序
- 🔐 自动签名:内置签名算法,确保请求安全
- 🔄 拦截器:支持请求和响应拦截器
- ⏱️ 超时控制:可配置请求超时时间
- 🚫 请求取消:支持使用 AbortController 取消请求
- 📦 轻量级:无其他依赖,体积小巧
## 安装
```bash
npm install glsk-fetch
```
## 使用方法
### 基本使用
```javascript
import Request from 'glsk-fetch';
const request = new Request({
baseURL: 'https://api.example.com',
appId: 'your_app_id',
appSecret: 'your_app_secret'
});
// GET 请求
request.get('/users').then(response => {
console.log(response.data);
});
// POST 请求
request.post('/users', {
name: 'John',
email: 'john@example.com'
}).then(response => {
console.log(response.data);
});
```
### 使用 async/await
```javascript
import Request from 'glsk-fetch';
const request = new Request({
baseURL: 'https://api.example.com',
appId: 'your_app_id',
appSecret: 'your_app_secret'
});
// 使用 async/await
async function fetchUsers() {
try {
const response = await request.get('/users');
console.log(response.data);
} catch (error) {
console.error('请求失败:', error.message);
}
}
fetchUsers();
```
### 拦截器
```javascript
// 请求拦截器
request.interceptors.request.use(
config => {
// 在发送请求之前做些什么
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 响应拦截器
request.interceptors.response.use(
response => {
// 对响应数据做点什么
return response;
},
error => {
// 对响应错误做点什么
return Promise.reject(error);
}
);
```
### 取消请求(简化版)
glsk-fetch 现在支持简化版的请求取消方式,请求方法直接返回带有 `abort()` 方法的对象:
```javascript
// 1. 发起请求
const requestPromise = request.get('/users');
// 2. 立即取消请求
requestPromise.abort();
// 3. 处理结果
requestPromise
.then(response => {
// 处理响应(不会执行,因为请求已被取消)
})
.catch(error => {
if (error.message === '请求已被取消') {
console.log('请求已被取消');
}
});
```
### 在 async/await 中使用取消功能
```javascript
// 发起请求
const requestPromise = request.get('/users');
// 立即取消请求
requestPromise.abort();
try {
// 等待请求结果
const response = await requestPromise;
console.log(response.data);
} catch (error) {
if (error.message === '请求已被取消') {
console.log('请求已被取消');
}
}
```
### 取消请求(标准版)
您也可以使用标准的 AbortController 方式:
```javascript
// 1. 创建 AbortController 实例
const controller = new AbortController();
// 2. 发起请求时传入 signal
request.get('/users', {
signal: controller.signal
}).then(response => {
// 处理响应
}).catch(error => {
if (error.message === '请求已被取消') {
console.log('请求已被取消');
}
});
// 3. 取消请求
controller.abort();
```
### 批量请求的选择性取消
```javascript
// 发起多个请求
const request1 = request.get('/users');
const request2 = request.get('/posts');
const request3 = request.get('/albums');
// 取消其中一个请求
request2.abort();
// 处理各个请求的结果
request1.then(response => console.log('用户数据:', response.data));
request2.catch(error => {
if (error.message === '请求已被取消') {
console.log('帖子请求被取消');
}
});
request3.then(response => console.log('相册数据:', response.data));
```
### 小程序中使用
在小程序中使用方式与 Web 端完全一致:
```javascript
const request = new Request({
baseURL: 'https://api.example.com',
appId: 'your_app_id',
appSecret: 'your_app_secret'
});
request.get('/users').then(response => {
console.log(response.data);
});
```
## API
### Request 构造函数
```javascript
const request = new Request({
baseURL: '', // 基础URL
timeout: 5000, // 超时时间(毫秒)
appId: '', // 应用ID(用于签名)
appSecret: '', // 应用密钥(用于签名)
headers: {} // 默认请求头
});
```
### 请求方法
所有请求方法都返回带有 `abort()` 方法的 Promise 对象:
- `request.get(url[, config])`
- `request.post(url[, data[, config]])`
- `request.put(url[, data[, config]])`
- `request.delete(url[, config])`
- `request.patch(url[, data[, config]])`
- `request.request(config)`
### 配置选项
```javascript
{
url: '', // 请求URL
method: 'GET', // 请求方法
baseURL: '', // 基础URL
headers: {}, // 请求头
params: {}, // URL参数
data: {}, // 请求体数据
timeout: 5000, // 超时时间
appId: '', // 应用ID
appSecret: '', // 应用密钥
signal: AbortSignal // 用于取消请求的信号
}
```
## License
MIT
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
{
"name": "glsk-fetch",
"version": "1.0.0",
"description": "一个兼容Web端与小程序端的请求库,带有签名算法和拦截器功能",
"main": "dist/index.js",
"module": "dist/index.esm.js",
"browser": "dist/index.umd.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "rollup -c rollup.config.mjs",
"dev": "rollup -c rollup.config.mjs -w",
"test": "jest"
},
"keywords": [
"fetch",
"http",
"request",
"axios",
"wechat",
"mini-program",
"signature"
],
"author": "Limin",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.24.0",
"@babel/preset-env": "^7.24.0",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^12.1.4",
"@types/crypto-js": "^4.2.2",
"jest": "^29.7.0",
"rollup": "^4.12.0",
"tslib": "^2.8.1",
"typescript": "^5.9.2"
},
"dependencies": {
"crypto-js": "^4.2.0"
}
}
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import terser from '@rollup/plugin-terser';
import typescript from '@rollup/plugin-typescript';
const extensions = ['.ts'];
export default {
input: 'src/index.ts',
plugins: [
// 允许 node_modules 中的包被解析
resolve({ extensions }),
// 将 CommonJS 模块转换为 ES6
commonjs(),
// 编译TypeScript
typescript(),
// 编译ES6+语法
babel({
extensions,
babelHelpers: 'bundled',
exclude: 'node_modules/**'
}),
// 压缩代码
terser()
],
output: [
{
file: 'dist/index.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/index.esm.js',
format: 'esm',
sourcemap: true
},
{
file: 'dist/index.umd.js',
format: 'umd',
name: 'GlskFetch',
sourcemap: true
}
]
};
\ No newline at end of file
import Request from './request';
export default Request;
\ No newline at end of file
import type { InterceptorHandler } from './types';
class InterceptorManager {
private handlers: (InterceptorHandler | null)[] = [];
/**
* 添加拦截器
* @param {Function} fulfilled 成功回调
* @param {Function} rejected 失败回调
* @returns {Function} 移除拦截器的函数
*/
use(
fulfilled: (value: any) => any | Promise<any>,
rejected?: (error: any) => any
): number {
const id = this.handlers.push({
fulfilled,
rejected: rejected || ((error: any) => Promise.reject(error))
}) - 1;
// 返回拦截器ID
return id;
}
/**
* 遍历执行拦截器
* @param {Function} fn 执行函数
*/
forEach(fn: (handler: InterceptorHandler) => void): void {
this.handlers.forEach(handler => {
if (handler !== null) {
fn(handler);
}
});
}
/**
* 移除拦截器
* @param {Number} id 拦截器ID
*/
eject(id: number): void {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
}
export default InterceptorManager;
\ No newline at end of file
import InterceptorManager from './interceptor';
import { generateSignature, type SignatureOptions } from './signature';
import type { RequestConfig, ResponseData } from './types';
interface Interceptors {
request: InterceptorManager;
response: InterceptorManager;
}
interface MiniProgramRequestOptions {
url: string;
method: string;
header?: RequestConfig['headers'];
timeout?: number;
data?: any;
success: (res: any) => void;
fail: (err: any) => void;
}
interface MiniProgram {
request: (options: MiniProgramRequestOptions) => void;
}
declare const wx: MiniProgram | undefined;
class Request {
defaults: RequestConfig;
interceptors: Interceptors;
private adapter: (config: RequestConfig) => Promise<any>;
constructor(config: RequestConfig = {}) {
this.defaults = {
baseURL: '',
timeout: 5000,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
appId: '',
appSecret: '',
...config
};
// 创建拦截器实例
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
// 在初始化时确定环境适配器
this.adapter = (function(that: Request) {
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
// 小程序环境
return that.miniprogramAdapter.bind(that);
} else {
// Web环境
return that.webAdapter.bind(that);
}
})(this);
}
/**
* 发起请求
* @param {Object} options 请求配置
* @returns {Promise & {abort: Function}} 可取消的请求Promise
*/
request(options: RequestConfig = {}): Promise<any> & { abort?: () => void } {
// 合并配置
const config: RequestConfig = { ...this.defaults, ...options };
// 创建AbortController用于请求取消
const controller = new AbortController();
// 如果配置中已存在signal,则需要合并处理
if (config.signal) {
// 当外部signal触发abort时,也触发内部controller的abort
config.signal.addEventListener('abort', () => {
controller.abort();
});
}
// 将controller.signal设置到config中
config.signal = controller.signal;
// 创建请求链
const chain: Array<(value: any) => any | Promise<any> | undefined> = [this.dispatchRequest.bind(this), () => undefined];
// 添加请求拦截器
this.interceptors.request.forEach(interceptor => {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
// 添加响应拦截器
this.interceptors.response.forEach(interceptor => {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
// 执行请求链
let promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift() as (value: any) => any, chain.shift() as (value: any) => any);
}
// 为Promise添加abort方法
const promiseWithAbort = promise as Promise<any> & { abort: () => void };
promiseWithAbort.abort = () => {
controller.abort();
};
return promiseWithAbort;
}
/**
* 处理请求分发
* @param {Object} config 请求配置
* @returns {Promise}
*/
dispatchRequest(config: RequestConfig): Promise<any> {
// 添加签名
const signedConfig = this.addSignature(config);
// 使用预先确定的适配器
return this.adapter(signedConfig);
}
/**
* 添加签名信息
* @param {Object} config 请求配置
* @returns {Object} 添加签名后的配置
*/
addSignature(config: RequestConfig): RequestConfig {
const { appId, appSecret } = config;
if (!appId || !appSecret) {
console.warn('缺少签名所需的应用ID或密钥');
return config;
}
// 获取请求参数
const params = { ...config.params };
// 生成签名
const signature = generateSignature({
appId,
appSecret,
params
} as SignatureOptions);
// 添加签名到请求头
config.headers = {
...config.headers,
'X-App-Id': appId,
'X-Nonce': signature.nonce,
'X-Timestamp': signature.timestamp,
'X-Sign': signature.sign
};
return config;
}
/**
* Web环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
webAdapter(config: RequestConfig): Promise<any> {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000,
signal
} = config;
// 构建完整URL
let fullURL = baseURL + url;
// 处理GET请求参数
if (method.toUpperCase() === 'GET' && Object.keys(params).length) {
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
}
// 创建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;
if (timeout && signal) {
// 只有当没有被取消时才设置超时
if (!signal.aborted) {
timeoutId = setTimeout(() => {
if (!signal.aborted) {
const event = new Event('abort');
signal.dispatchEvent(event);
}
}, timeout);
}
}
// 发起请求
return fetch(fullURL, fetchOptions)
.then(response => {
if (timeoutId) clearTimeout(timeoutId);
return response.json().catch(() => response.text());
})
.then(data => ({
data,
status: 200,
statusText: 'OK',
headers: {},
config
}))
.catch(error => {
if (timeoutId) clearTimeout(timeoutId);
// 处理取消请求的情况
if (error.name === 'AbortError' || (signal && signal.aborted)) {
throw new Error('请求已被取消');
}
throw error;
});
}
/**
* 小程序环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
miniprogramAdapter(config: RequestConfig): Promise<any> {
return new Promise((resolve, reject) => {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000
} = config;
// 构建完整URL
let fullURL = baseURL + url;
// 处理GET请求参数
if (method.toUpperCase() === 'GET' && Object.keys(params).length) {
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
}
// 小程序请求选项
const requestOption: MiniProgramRequestOptions = {
url: fullURL,
method: method.toUpperCase(),
header: headers,
timeout,
success: (res) => {
resolve({
data: res.data,
status: res.statusCode,
statusText: res.errMsg,
headers: res.header,
config
});
},
fail: (err) => {
reject(err);
}
};
// 处理请求体
if (method.toUpperCase() !== 'GET') {
requestOption.data = data;
}
// 发起请求
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
wx.request(requestOption);
} else {
reject(new Error('当前环境不支持小程序请求'));
}
});
}
}
// 添加别名方法
(['get', 'post', 'put', 'delete', 'patch'] as const).forEach(method => {
(Request.prototype as any)[method] = function(url: string, dataOrConfig?: any, config: RequestConfig = {}) {
let finalConfig = { ...config };
// 根据方法类型处理参数
if (method === 'get' || method === 'delete') {
// 对于GET、DELETE方法,第二个参数是config
if (dataOrConfig) {
finalConfig = { ...finalConfig, ...dataOrConfig };
}
} else {
// 对于POST、PUT、PATCH方法,第二个参数是data,第三个参数是config
finalConfig.data = dataOrConfig;
}
return this.request({
url,
method: method.toUpperCase(),
...finalConfig
});
};
});
export default Request;
\ No newline at end of file
import CryptoJS from 'crypto-js';
export interface SignatureOptions {
appId: string;
appSecret: string;
params?: Record<string, any>;
}
export interface SignatureResult {
nonce: string;
timestamp: string;
sign: string;
}
/**
* 生成UUID
* @returns {string} UUID
*/
function generateUUID(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* 生成签名
* @param {Object} options 签名参数
* @param {string} options.appId 应用ID
* @param {string} options.appSecret 应用密钥
* @param {Object} options.params 请求参数
* @returns {Object} 签名信息
*/
export function generateSignature({ appId, appSecret, params = {} }: SignatureOptions): SignatureResult {
// 生成随机字符串
const nonce = generateUUID();
// 生成时间戳
const timestamp = Date.now().toString();
// 准备签名参数
const signParams: Record<string, string> = {
'X-App-Id': appId,
'X-Nonce': nonce,
'X-Timestamp': timestamp,
...params
};
// 1. 将所有参数(除sign外)按参数名ASCII码从小到大排序
const sortedKeys = Object.keys(signParams).sort();
// 2. 使用URL键值对格式拼接成字符串
const stringToSign = sortedKeys
.map(key => `${key}=${signParams[key]}`)
.join('&');
// 3. 拼接应用密钥
const signString = `${stringToSign}&secret=${appSecret}`;
// 4. 使用HMAC-SHA256算法计算签名
const sign = CryptoJS.HmacSHA256(signString, appSecret).toString();
return {
nonce,
timestamp,
sign
};
}
\ No newline at end of file
export interface RequestHeaders {
'Content-Type'?: string;
'X-App-Id'?: string;
'X-Nonce'?: string;
'X-Timestamp'?: string;
'X-Sign'?: string;
[key: string]: string | undefined;
}
export interface RequestConfig {
url?: string;
method?: string;
baseURL?: string;
headers?: Record<string, string>;
params?: Record<string, any>;
data?: any;
timeout?: number;
appId?: string;
appSecret?: string;
signal?: AbortSignal; // 添加signal属性支持请求取消
}
export interface ResponseData {
data: any;
status: number;
statusText: string;
headers: Record<string, any>;
config: RequestConfig;
}
export interface InterceptorHandler {
fulfilled: (value: any) => any | Promise<any>;
rejected: (error: any) => any;
}
export interface InterceptorManagerInstance {
use(fulfilled: (value: any) => any | Promise<any>, rejected?: (error: any) => any): number;
eject(id: number): void;
}
export interface RequestInstance {
defaults: RequestConfig;
interceptors: {
request: InterceptorManagerInstance;
response: InterceptorManagerInstance;
};
request(config?: RequestConfig): Promise<any>;
get(url: string, config?: RequestConfig): Promise<any>;
delete(url: string, config?: RequestConfig): Promise<any>;
head(url: string, config?: RequestConfig): Promise<any>;
options(url: string, config?: RequestConfig): Promise<any>;
post(url: string, data?: any, config?: RequestConfig): Promise<any>;
put(url: string, data?: any, config?: RequestConfig): Promise<any>;
patch(url: string, data?: any, config?: RequestConfig): Promise<any>;
}
\ No newline at end of file
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2015",
"moduleResolution": "node",
"declaration": true,
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}
\ 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!