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 🙏

© 2026 – Pkg Stats / Ryan Hefner

uni-smart-request

v0.1.0

Published

A flexible uni-app request plugin with token auth, refresh queue, encryption hooks, and loading management.

Readme

@your-scope/uni-smart-request

一个功能强大的 uni-app 请求工具,支持 Token 自动注入、401 刷新队列管理、全局 Loading 控制、数据加解密钩子与自定义错误码映射。

📦 安装

npm i @your-scope/uni-smart-request

🚀 快速开始

1. 初始化请求实例

创建一个 API 配置文件(如 src/api/index.js):

// src/api/index.js
import { createUniRequest } from '@your-scope/uni-smart-request';

// 创建请求实例
const request = createUniRequest({
  // 基础 URL
  baseUrl: 'https://api.example.com',
  
  // Token 相关配置
  getToken: () => uni.getStorageSync('token'), // 获取 Token 的方法
  tokenHeaderKey: 'Authorization', // Token 头部键名
  formatToken: (token) => `Bearer ${token}`, // Token 格式化
  
  // 加载提示配置
  defaultLoadingTitle: '加载中...',
  
  // 错误码映射
  errorCodeMap: {
    400: '请求参数错误',
    401: '未授权,请重新登录',
    403: '拒绝访问',
    404: '请求资源不存在',
    500: '服务器内部错误',
    default: '请求失败,请稍后重试'
  },
  
  // Token 刷新处理
  refreshToken: async () => {
    // 实现 Token 刷新逻辑
    const refreshToken = uni.getStorageSync('refreshToken');
    const res = await uni.request({
      url: 'https://api.example.com/refresh-token',
      method: 'POST',
      data: { refreshToken }
    });
    const { token, refreshToken: newRefreshToken } = res[1].data;
    uni.setStorageSync('token', token);
    uni.setStorageSync('refreshToken', newRefreshToken);
  }
});

export default request;

2. 基本使用方法

// 导入请求实例
import request from './api/index';

// 1. GET 请求
async function getUserInfo() {
  try {
    const res = await request.get('/user/info', {
      params: { userId: 123 },
      loading: true // 显示加载提示
    });
    console.log(res.data);
  } catch (error) {
    console.error(error);
  }
}

// 2. POST 请求
async function login() {
  try {
    const res = await request.post('/auth/login', {
      username: 'admin',
      password: '123456'
    }, {
      loading: { title: '登录中...' } // 自定义加载提示文字
    });
    console.log(res.data);
  } catch (error) {
    console.error(error);
  }
}

// 3. 通用请求方式
async function customRequest() {
  try {
    const res = await request({
      url: '/custom/endpoint',
      method: 'PUT',
      data: { key: 'value' },
      header: {
        'Content-Type': 'application/json'
      },
      isToken: true, // 强制携带 Token
      loading: true
    });
    console.log(res.data);
  } catch (error) {
    console.error(error);
  }
}

📋 高级配置选项

1. 完整配置项

const request = createUniRequest({
  // 基础配置
  baseUrl: 'https://api.example.com', // 基础 URL
  timeoutMs: 30000, // 请求超时时间(毫秒)
  
  // Token 管理
  getToken: () => uni.getStorageSync('token'), // Token 获取函数
  tokenHeaderKey: 'Authorization', // Token 头部键名
  formatToken: (token) => `Bearer ${token}`, // Token 格式化函数
  withTokenByDefault: true, // 是否默认携带 Token
  
  // 参数序列化
  serializeParams: (params) => { /* 自定义参数序列化逻辑 */ },
  
  // 数据加解密
  enableEncrypt: true, // 是否启用加解密
  encrypt: (data) => { /* 加密逻辑 */ }, // 加密函数
  decrypt: (data) => { /* 解密逻辑 */ }, // 解密函数
  
  // UI 交互钩子
  showLoading: (title) => { /* 自定义显示加载 */ },
  hideLoading: () => { /* 自定义隐藏加载 */ },
  defaultLoadingTitle: '加载中...', // 默认加载提示文字
  toast: (message) => { /* 自定义提示函数 */ },
  confirm: (message) => { /* 自定义确认对话框 */ },
  
  // 错误处理
  errorCodeMap: { /* 自定义错误码映射 */ },
  
  // Token 刷新
  refreshToken: async () => { /* Token 刷新逻辑 */ },
  
  // 平台特定头部处理
  platformHeaderResolver: (headers) => { /* 自定义头部处理 */ }
});

2. 数据加解密示例

const request = createUniRequest({
  enableEncrypt: true,
  // 加密示例 - 这里使用简单的 Base64(实际项目中应使用更安全的加密方式)
  encrypt: (data) => {
    const str = JSON.stringify(data);
    // 这里仅为示例,实际应使用加密库
    return btoa(unescape(encodeURIComponent(str)));
  },
  // 解密示例
  decrypt: (data) => {
    try {
      // 这里仅为示例,实际应使用加密库
      const str = decodeURIComponent(escape(atob(data)));
      return JSON.parse(str);
    } catch (e) {
      return data; // 解密失败时返回原始数据
    }
  }
});

3. 自定义 UI 交互

const request = createUniRequest({
  showLoading: (title) => {
    // 使用自定义的 loading 组件
    // 例如使用 Vant Weapp 的 Toast
    uni.showLoading({ title, mask: true });
  },
  hideLoading: () => {
    uni.hideLoading();
  },
  toast: (message) => {
    // 使用自定义的提示组件
    uni.showToast({ title: message, icon: 'none', duration: 2000 });
  }
});

🔧 请求配置选项

每个请求可以单独配置以下选项:

request({
  url: '/api/path', // 请求路径
  method: 'POST', // 请求方法
  params: { id: 123 }, // URL 查询参数
  data: { name: 'test' }, // 请求体数据
  header: { 'Content-Type': 'application/json' }, // 请求头
  timeout: 15000, // 超时时间(毫秒)
  loading: true, // 或 { title: '加载中...' }
  isToken: true // 是否携带 Token,优先级高于默认配置
});

📱 平台兼容性

该插件在 uni-app 支持的所有平台(iOS、Android、H5、微信小程序等)上均可使用。对于不同平台的特殊头部需求,可以通过 platformHeaderResolver 进行处理。

🔒 Token 刷新队列机制

当遇到 401 未授权错误时,插件会:

  1. 暂停后续所有请求
  2. 触发 refreshToken 函数
  3. 刷新成功后,自动重新发起之前暂停的请求
  4. 刷新失败时,所有请求都会被拒绝

🛠️ 构建与发布

# 构建 TypeScript 源码
npm run build

# 构建 UMD 格式(用于 CDN 引用)
npm run build:dist

# 发布到 npm
npm publish --access public

📄 许可证

MIT