npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@dreamjser/http-client

v1.0.11

Published

A lightweight HTTP client with XHR and Fetch support

Downloads

19

Readme

HTTP Client

一个轻量级的 HTTP 客户端,支持 XHR 和 Fetch API,具有请求队列、拦截器、进度监控等功能。

特性

  • 支持 XHR 和 Fetch API(自动选择)
  • 基于 Promise 的异步请求
  • TypeScript 支持
  • 请求和响应拦截器
  • 请求队列和并发控制
  • 上传和下载进度监控
  • 请求超时处理
  • 跨域凭证支持
  • 自定义请求头
  • 简单易用的 API

安装

npm install http-client
# 或
yarn add http-client
# 或
pnpm add http-client

使用方法

基本使用

import { HttpClient } from 'http-client'

// 创建实例
const client = new HttpClient({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  maxConcurrent: 3,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json'
  }
})

// GET 请求
const getData = async () => {
  try {
    const response = await client.get('/users')
    console.log(response.data)
  } catch (error) {
    console.error(error)
  }
}

// POST 请求
const createData = async () => {
  try {
    const response = await client.post('/users', {
      name: 'John Doe',
      email: '[email protected]'
    })
    console.log(response.data)
  } catch (error) {
    console.error(error)
  }
}

文件上传(带进度监控)

const uploadFile = async (file: File) => {
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await client.post('/upload', formData, {
      onUploadProgress: (progress) => {
        console.log(`上传进度: ${progress}%`)
      }
    })
    console.log(response.data)
  } catch (error) {
    console.error(error)
  }
}

并发请求

const fetchMultipleData = async () => {
  try {
    const [user, posts, comments] = await Promise.all([
      client.get('/users/1'),
      client.get('/posts?userId=1'),
      client.get('/comments?postId=1')
    ])
    console.log(user.data, posts.data, comments.data)
  } catch (error) {
    console.error(error)
  }
}

使用拦截器

// 添加请求拦截器
client.useRequestInterceptor({
  onRequest: (config) => {
    // 添加认证信息
    config.headers = {
      ...config.headers,
      'Authorization': 'Bearer token'
    }
    return config
  },
  onRequestError: (error) => {
    console.error('请求错误:', error)
    return error
  }
})

// 添加响应拦截器
client.useResponseInterceptor({
  onResponse: (value) => {
    // 处理响应数据
    const { response, config } = value
    if (response.status === 200) {
      return response
    }
    throw new Error('请求失败')
  },
  onResponseError: (error) => {
    console.error('响应错误:', error)
    return error
  }
})

API

HttpClient

构造函数

new HttpClient(config?: HttpClientConfig)

配置选项

interface HttpClientConfig {
  baseURL?: string          // 基础 URL
  timeout?: number          // 请求超时时间(毫秒)
  maxConcurrent?: number    // 最大并发请求数
  withCredentials?: boolean // 是否发送跨域凭证
  headers?: Record<string, string> // 默认请求头
}

请求方法

// 通用请求方法
request<T>(config: RequestConfig): Promise<Response<T>>

// 快捷方法
get<T>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<Response<T>>
post<T>(url: string, data?: any, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>): Promise<Response<T>>
put<T>(url: string, data?: any, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>): Promise<Response<T>>
delete<T>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<Response<T>>
patch<T>(url: string, data?: any, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>): Promise<Response<T>>

请求配置

interface RequestConfig {
  url: string
  method?: HttpMethod
  headers?: Record<string, string>
  data?: any
  timeout?: number
  withCredentials?: boolean
  responseType?: XMLHttpRequestResponseType
  onUploadProgress?: (progress: number) => void
  onDownloadProgress?: (progress: number) => void
}

响应格式

interface Response<T = any> {
  data: T
  status: number
  statusText: string
  headers: Record<string, string>
}

拦截器

interface RequestInterceptor {
  onRequest?: (config: RequestConfig) => RequestConfig | Promise<RequestConfig>
  onRequestError?: (error: any) => any
}

interface ResponseConfig {
  response: Response
  config: RequestConfig
  resolve: (value: Response) => void
  reject: (reason?: any) => void
}

interface ResponseInterceptor {
  onResponse?: <T>(value: ResponseConfig) => Response<T> | Promise<Response<T>>
  onResponseError?: (error: any) => any
}

开发

# 安装依赖
pnpm install

# 开发模式运行示例
pnpm example:dev

# 构建
pnpm build

# 运行测试
pnpm test

# 监视模式运行测试
pnpm test:watch

# 生成测试覆盖率报告
pnpm test:coverage

# 代码检查
pnpm lint

示例

项目包含一个完整的示例应用,展示了 HTTP 客户端的主要功能:

  1. 基本请求(GET/POST)
  2. 文件上传(带进度条)
  3. 并发请求
  4. 拦截器

运行示例:

# 开发模式
pnpm example:dev

# 构建
pnpm example:build

# 预览
pnpm example:preview

License

MIT