JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 23
  • Score
    100M100P100Q72173F
  • License MIT

一个极简的函数,用于获取 accessToken

Package Exports

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (use-token-manager) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    use-token-manager

    一个极简的函数,用于获取 accessToken。

    特性

    • 极简设计: 只专注一件事 - 获取 accessToken
    • 🚀 零配置: 开箱即用,最少配置
    • 📦 完整 TypeScript 支持: 类型安全
    • 🎯 轻量级: 代码量极少,性能优异
    • 🌐 通用: 不依赖任何框架,可在任何 JavaScript 环境中使用
    • 🛡️ 静默处理: 失败时不抛异常,返回 null

    安装

    npm install use-token-manager
    # 或
    yarn add use-token-manager

    使用方法

    基础用法

    import { getAccessToken } from 'use-token-manager';
    
    async function main() {
      const accessToken = await getAccessToken({
        tokenEndpoint: 'https://api.example.com/auth/token',
      });
    
      if (accessToken) {
        console.log('Token:', accessToken);
      } else {
        console.log('获取 token 失败');
      }
    }
    
    main();

    自定义请求方法和头部

    import { getAccessToken } from 'use-token-manager';
    
    async function fetchToken() {
      const accessToken = await getAccessToken({
        tokenEndpoint: 'https://api.example.com/auth/token',
        method: 'POST', // 默认 GET
        headers: {
          'X-API-Version': '1.0',
          'Authorization': 'Bearer static-key',
        },
      });
    
      return accessToken;
    }

    在 HTTP 请求中使用 token

    import { getAccessToken } from 'use-token-manager';
    
    async function fetchUserProfile() {
      // 先获取 token
      const accessToken = await getAccessToken({
        tokenEndpoint: 'https://api.example.com/auth/token',
      });
    
      if (!accessToken) {
        throw new Error('无法获取访问令牌');
      }
    
      // 使用 token 调用 API
      const response = await fetch('https://api.example.com/user/profile', {
        headers: {
          'Authorization': `Bearer ${accessToken}`,
        },
      });
    
      return response.json();
    }

    React 中使用(配合 useEffect)

    import React, { useState, useEffect } from 'react';
    import { getAccessToken } from 'use-token-manager';
    
    function TokenDisplay() {
      const [accessToken, setAccessToken] = useState(null);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        async function fetchToken() {
          const token = await getAccessToken({
            tokenEndpoint: 'https://api.example.com/auth/token',
          });
          setAccessToken(token);
          setLoading(false);
        }
    
        fetchToken();
      }, []);
    
      if (loading) return <div>加载中...</div>;
    
      return (
        <div>
          {accessToken ? (
            <p>Token: {accessToken}</p>
          ) : (
            <p>获取 token 失败</p>
          )}
        </div>
      );
    }

    Node.js 中使用

    const { getAccessToken } = require('use-token-manager');
    
    async function authenticateAndCallAPI() {
      try {
        const token = await getAccessToken({
          tokenEndpoint: 'https://api.example.com/auth/token',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
        });
    
        if (token) {
          // 使用 token 调用其他 API
          console.log('认证成功,Token:', token);
        } else {
          console.log('认证失败');
        }
      } catch (error) {
        console.error('发生错误:', error);
      }
    }

    API 参考

    getAccessToken(config)

    参数

    参数名 类型 必需 默认值 描述
    tokenEndpoint string - 获取 token 的 API 端点
    method string 'GET' HTTP 请求方法 ('GET', 'POST', 'PUT', 'PATCH')
    headers object {} 请求头

    返回值

    返回 Promise<string | null>

    • 成功时返回 accessToken 字符串
    • 失败时返回 null
    • 不会抛出异常

    后端 API 要求

    你的后端 API 需要返回包含 accessToken 字段的 JSON 响应:

    {
      "accessToken": "your-access-token-here"
    }

    支持的 HTTP 状态码:

    • 200 OK: 成功获取 token
    • 304 Not Modified: Token 未改变(函数版本下会返回 null)
    • 301 Moved Permanently: 永久重定向(函数版本下会返回 null)

    工作原理

    1. 发起请求: 根据配置向指定端点发起 HTTP 请求
    2. 解析响应: 从响应中提取 accessToken 字段
    3. 返回结果: 成功时返回 token 字符串,失败时返回 null
    4. 错误处理: 网络错误或解析失败时静默返回 null

    设计哲学

    • 极简主义: 只做一件事,并把它做好
    • 通用性: 不依赖任何框架,适用于所有 JavaScript 环境
    • 类型安全: 完整的 TypeScript 支持
    • 静默处理: 不抛异常,让应用保持稳定
    • 函数式: 纯函数设计,无副作用

    使用场景

    • ✅ Node.js 服务端应用
    • ✅ 浏览器前端应用
    • ✅ React/Vue/Angular 等框架应用
    • ✅ 微信小程序(需要 fetch polyfill)
    • ✅ Electron 桌面应用
    • ✅ React Native 移动应用

    注意事项

    • 确保你的 API 端点返回包含 accessToken 字段的 JSON 响应
    • 函数是异步的,记得使用 await.then()
    • 失败时返回 null,不会抛出异常
    • 在浏览器中使用时,请注意 CORS 策略

    更新日志

    v2.1.0

    • 🎉 重大更新: 从 React Hook 改为通用函数
    • 🌐 通用性: 移除 React 依赖,适用于所有 JavaScript 环境
    • 📦 更轻量: 移除不必要的依赖
    • 🔧 API 变更: useTokenManager()getAccessToken()

    v2.0.0

    • ✨ 简化为极简版本,只返回 accessToken
    • ❌ 移除长短 token 概念

    v1.x.x

    • React Hook 版本(已废弃)

    许可证

    MIT

    贡献

    欢迎提交 Issue 和 Pull Request!