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

openx-js-sdk

v0.0.26

Published

📌 **版本历史** **v0.0.26 – 2025-12-09** * 新增 skipInterceptorsRequest 请求配置项 允许业务方在单个接口级别跳过 interceptorsRequest 对入参的结构化处理。

Readme

openx-js-sdk 使用说明文档

📌 版本历史 v0.0.26 – 2025-12-09

  • 新增 skipInterceptorsRequest 请求配置项 允许业务方在单个接口级别跳过 interceptorsRequest 对入参的结构化处理。

v0.0.25 – 2025-12-09

  • 新增 interceptorResult 方法 允许业务方在请求完成后对最终返回结构进行自定义改造。
  • 埋点业务开发环境关闭加载 v0.0.24 – 2025-12-08
  • openx 实例新增 logOut 方法用于业务方主动触发退出登录逻辑。
  • 针对 5014、5007、重复获取jwt情况,SDK 内部新增自动执行清理机制。

v0.0.23 – 2025-12-08

  • getRefreshToken 新增机构账户5019情况返回

v0.0.22 – 2025-12-08

  • openx 实例新增 getRefreshToken 方法用于单独设置jwt

v0.0.21 – 2025-12-08

  • 新增 interceptorsRequest 请求拦截器钩子用于统一处理接口请求拦截
  • 原字段 response 已标记为兼容字段,统一替换为 interceptorsResponse

v0.0.20 – 2025-11-30 处理埋点业务多应用 app_id 混合使用问题

v0.0.17 – 2025-11-30

  • 处理 jwt 5013 返回数据问题

v0.0.15 – 2025-11-28

  • tracker 初次加载队列阻塞问题处理

v0.0.14 – 2025-11-27

  • 新增 withCredentials 配置项,默认携带,可在跨域或公共接口场景中通过 withCredentials: false 禁止附带 Cookie。

v0.0.13 – 2025-11-24

  • 新增 tracker 配置项,用于开启埋点管理
  • 新增 overrideTrackerAppId 配置项,覆盖原有埋点 appId 行为

v0.0.12 – 2025-11-21

  • 新增 verifyRealName 配置项,用于开启实名认证阻断机制(429001)
  • 优化内部正则 URL 匹配逻辑,支持 /proxy-sdk-jwt 等带短横线的代理路径

1. SDK 介绍

openx-js-sdk 面向 CNKI 研学、授权等业务场景,是一个轻量级、可扩展的前端通用 SDK,封装了:

  • 🔑 JWT 自动获取 & 自动续期
  • 🌍 统一接口代理(development/test/production)
  • ⚙️ get/post 请求封装
  • 🚦 可配置的全局响应处理器
  • 💡 IP 获取、Cookie 工具、本地缓存管理
  • 📊 埋点(Tracker)按需加载与 AppId 统一管理

业务开发者只需使用公开 API,无需关心底层网络、身份态、埋点加载等逻辑。


2. 安装方式

npm install openx-js-sdk
# 或
yarn add openx-js-sdk
# 或
pnpm add openx-js-sdk

3. 快速开始

3.1 初始化(推荐在应用入口处执行)

import openx from 'openx-js-sdk'

openx.config({
  appId: '',                // 当前应用 AppId(JWT & 埋点)
  env: 'test',              // development | test | production
  verifyRealName: true,     // 开启实名认证自动阻断
  timeout: 5000,            // axios 超时时间,默认 5000ms
  tracker: true,            // 是否开启埋点(按需加载)
  overrideTrackerAppId: true, // 是否覆盖埋点默认 AppId(统一 AppId)
  interceptorsResponse: (res) => {
    // 可选:全局业务响应处理
  },
  interceptorsRequest: (res) => {
    // 可选:全局请求拦截器钩子
      config.headers['X-Requested-With'] = ''
      return config
  },
    interceptorResult(res) {
        return res.data  // 返回结构可由业务方自行决定
    },
  proxy: {
      /**
       * SDK 额外要求的代理配置:
       * - 因为 SDK 内部会自动调用 JWT / IP 相关接口,因此业务项目必须提供与 SDK 通信的本地代理前缀
       * - /proxy-sdk-jwt /proxy-sdk-ip 前缀只在 development(本地开发)环境下使用
       * - 测试 / 生产环境不会使用这些代理,构建后会根据 env 自动转换为 target 真实地址
       * - 业务方也可以传入其他接口服务;打包时 SDK 会自动做替换
       */
    '/proxy-sdk-jwt': {
      open: false,
      ws: false,
      target: 'https://xtest.cnki.net/coreapi/api',
      changeOrigin: true,
      pathRewrite: { '^/proxy-sdk-jwt': '/' },
      headers: {
        origin: 'https://x.cnki.net',
        referer: 'https://x.cnki.net'
      }
    },
    '/proxy-sdk-ip': {
      open: false,
      ws: false,
      target: 'https://xtest.cnki.net/ip',
      changeOrigin: true,
      pathRewrite: { '^/proxy-sdk-ip': '/' },
      headers: {
        origin: 'https://x.cnki.net',
        referer: 'https://x.cnki.net'
      }
    }
  }
})

// ready 会自动获取或刷新 JWT
await openx.ready()

4. 请求接口

4.1 GET 请求

const res = await openx.getAction('/proxy-ix/endpoint', {
  name: 'charlie'
})

4.2 POST 请求

const res = await openx.postAction('/proxy-ix/endpoint', {
  name: 'charlie'
})

SDK 会自动:

  • 携带 JWT
  • 处理 JWT 过期自动续期
  • 根据 proxy 自动切换 BaseURL
  • 对响应进行封装

4.3 支持第三个参数配置 Headers / Timeout 等 Axios 配置

业务方可以为 getAction 与 postAction 传递 第三个参数,用于设置额外的请求配置,例如自定义 Header、超时时间、携带特殊标记字段等。 示例:传入自定义 Headers

const res = await openx.postAction(
  '/proxy-ix/endpoint',
  { name: 'charlie' },
  {
      timeout: 8000,
      withCredentials: true,
    headers: {
      'X-From': 'xai-writing',
      'X-Request-ID': 'abc123'
    }
  }
)

5. JWT 管理

5.1 获取当前 JWT

const token = openx.getJwt()

5.2 清除 JWT

openx.removeJwt()

6. 配置项说明(ConfigOptions)

openx.config({
  appId: string,                          // 当前应用的 appId
  env?: 'development' | 'test' | 'production',
  verifyRealName?: boolean,               // 是否开启实名认证自动阻断
  timeout?: number,                       // axios 超时时间
  withCredentials?: boolean,              // 是否默认携带cookie
  proxy?: Record<string, any>,            // 本地代理配置
  response?: (res: any) => any,           // 全局响应处理
  interceptorsResponse?: (res: any) => any,           // 全局请求响应处理
  interceptorsRequest?: (res: any) => any,           // 全局请求拦截处理
  interceptorResult?: (res: any) => any,           // 全局返回结构拦截处理
  tracker?: boolean,                      // 是否启用埋点(按需加载)
  overrideTrackerAppId?: boolean          // 是否覆盖默认埋点 AppId(统一 AppId)
})

7. 获取用户 IP

const ip = await openx.getUserIp()

SDK 会自动缓存 IP,避免重复请求。


8. 埋点管理(Tracker)

openx-js-sdk 内置埋点模块,采用 按需加载策略(Lazy Load),解决旧项目中必须手动引入 sensors.min.js 的问题。

只有在显式开启埋点时才会自动加载脚本:

tracker: true

8.1 tracker 的作用

| 配置 | 行为 | | -------------------- | ----------------------------------- | | tracker: false(默认) | 不加载 sensors,不初始化埋点,全程 0 成本 | | tracker: true | 按需加载 sensors,并提供全局 sta_api 用于事件上报 |


8.2 统一 AppId(解决历史混用问题)

旧项目中存在多个 AppId 混用、冲突、覆盖的问题。 SDK 提供统一管理能力:

overrideTrackerAppId: true

启用后:

  • 强制整个应用使用 openx.config().appId
  • sensors 默认 AppId 会被自动覆盖
  • 所有事件上报都归属同一 AppId
  • 解决多子系统混用、旧代码遗留 AppId 的混乱问题

9. 退出登录管理

sdk 提供统一的 退出登录 方法,用于在业务系统中安全清理用户登录态,包括: 清理所有与研学平台相关的 Cookie 清理 JWT(通过 cnki-x-jwt 管理的 token) 返回结构化结果,便于业务层进行后续处理(如跳转登录页、弹出提示等)

  • 示例:业务方调用
import openx from 'openx-js-sdk'

const result = openx.logOut()

if (result.code===0) {
  console.log('用户已退出登录', result)
  // 可选:跳转登录页
  // window.location.href = '/login'
} else {
  console.error('退出登录失败', result.error)
}
  • 退出成功返回示例
{
  "code": 0,
  "message": "退出登录成功",
  "clearedCookies": [
    "LID",
    "AID"
  ],
  "clearedJwtKey": "appId"
}

10. 完整示例

import openx from 'openx-js-sdk'

// 初始化
openx.config({
  appId: 'xxx',
  env: 'development',
  proxy: {},
  verifyRealName: true,
  tracker: true,
  overrideTrackerAppId: true,
    interceptorsResponse: (res) => {
    if (res.data.code === 5014) {
      console.log('登录过期,业务方自行处理')
    }
  },
  interceptorsRequest: (config) => {
     config.headers['X-Requested-With'] = ''
     return config
  }
})

await openx.ready()

// 示例请求
const info = await openx.getAction('/proxy-ix/user/getUserInfo',{},{
    withCredentials: true,// 单独设置接口携带cookie项
    timeout: 10000 // 单独设置接口超时时间
})
console.log(info)