@sparta-utils/stream-request
v1.0.6
Published
用于流式传输HTTP请求的轻量级实用程序
Readme
@sparta-utils/stream-request
一个支持 流式响应(如 SSE、AI 多轮对话等)的轻量级请求工具库,支持逐段处理、超时、取消、自动 JSON 行解析,并在请求结束时返回完整响应信息。
✨ 特性
- ✅ 流式逐段处理响应数据(边下边处理)
- ✅ 自动 JSON 行解析(可选)
- ✅ 支持 请求中断(AbortSignal)、超时控制
- ✅ 请求完成时返回完整响应内容和 HTTP 元信息
- ✅ 完全自定义请求头,支持所有 HTTP 方法
- ✅ 支持上传
FormData
📦 安装
npm install @sparta-utils/stream-request
# 或
yarn add @sparta-utils/stream-request🚀 快速上手
import { streamRequest } from '@sparta-utils/stream-request';
streamRequest('https://your-api.com/stream', {
method: 'POST',
body: { prompt: '你好 AI' },
headers: {
Authorization: 'Bearer your-token',
'Custom-Header': '自定义内容'
},
autoParseJSON: true, // 自动解析每行 JSON
onMessage: (text) => {
console.log('收到分段数据:', text);
},
onDone: (fullText, responseInfo) => {
console.log('✅ 请求完成,完整内容:', fullText);
console.log('HTTP 元信息:', responseInfo);
},
onError: (err) => {
console.error('❌ 出错:', err);
},
timeout: 10000 // 10 秒超时
});📚 参数说明
| 参数名 | 类型 | 说明 |
| ----------------- | ------------------------ | ---- |
| url | string | 请求地址 |
| method | 'GET' \| 'POST' \| ... | 请求方法,默认 GET |
| headers | Record<string, string> | 自定义请求头 |
| body | object \| FormData | 请求体(会自动判断是否 FormData) |
| onMessage | (text: string) => void | 流式分段回调(每接收到一段数据调用一次) |
| onDone | (fullText: string, responseInfo: ResponseInfo) => void | 请求结束回调,返回完整文本和 HTTP 元信息 |
| onError | (error: any) => void | 错误回调 |
| autoParseJSON | boolean | 自动按行解析 JSON(解析失败会保留原文) |
| decoderEncoding | string | 编码,默认 utf-8 |
| timeout | number(毫秒) | 超时时间,到达后自动中断 |
| signal | AbortSignal | 外部中断信号对象 |
| lineSeparator | string | 流分段分隔符,默认 \n |
| onProgress | (bytes: number) => void| 已接收字节数实时回调 |
| onRawChunk | (chunk: Uint8Array) => void | 原始二进制块回调 |
ResponseInfo 结构
interface ResponseInfo {
status: number
statusText: string
headers: Record<string, string>
url: string
parsedBody?: any // 当 autoParseJSON=true 且解析成功时存在
}⏹ 中断请求
const controller = new AbortController();
streamRequest('/api/stream', {
signal: controller.signal,
onMessage: console.log,
onError: (err) => console.error(err)
});
// 3 秒后中断请求
setTimeout(() => {
controller.abort();
}, 3000);🌍 常用 HTTP 方法示例
// PUT 更新
streamRequest('/api/item/123', {
method: 'PUT',
body: { name: '新名称' },
headers: { Authorization: 'Bearer xxx' },
onMessage: (text) => console.log('PUT 响应片段:', text)
});
// DELETE 删除
streamRequest('/api/item/123', {
method: 'DELETE',
headers: { Authorization: 'Bearer xxx' },
onMessage: (text) => console.log('DELETE 响应片段:', text)
});🔍 进阶:文件上传 + 流式处理
const formData = new FormData();
formData.append('file', fileInput.files[0]);
streamRequest('/api/upload', {
method: 'POST',
body: formData,
onProgress: (bytes) => {
console.log('已接收字节:', bytes);
},
onMessage: (text) => {
console.log('上传进度:', text);
},
onDone: (fullText) => {
console.log('上传完成:', fullText);
}
});⚠️ 注意事项
- 超时 或 外部中断 会触发
onError,不会重试。 - autoParseJSON 会尝试按行解析 JSON,适合 SSE/AI 流;如果数据不是标准 JSON 行,请设为
false。 - 流模式下的
fullText是所有片段拼接结果,如果后端最后会返回完整 JSON,可以在onDone里解析。
📄 许可证
MIT License © 2025
