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

use-token-manager

v2.8.0

Published

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

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!