跳到主要内容

使用 JS 类库

内置类库列表

  • Encode、Decode 库
    • crypto-js(v3.1.9-1):编码 / 解码库,常用的编码解码方式基本都有,如 Base64、MD5、SHA、HMAC、AES 等等。
      • 注意:只能 require 整个模块,不能单独 require 类库里的某个子模块,具体看本文档末尾说明。
    • atob(v2.1.2):Base64 解码
    • btoa(v1.2.1):Base64 编码
    • tv4(v1.3.0):JSONSchema 校验库
    • xml2js(v0.4.19):XML 转 JSON

通过 require方法可以直接使用 Apifox 内置的 JS 类库。

var cryptoJs = require("crypto-js");
console.log(cryptoJs.SHA256("Message"));

使用方式

// 场景一:SHA256加密,输出Base64
// 定义要加密的消息
const message = "Hello, World!";
// 使用SHA256算法进行加密
const hash = CryptoJS.SHA256(message);
// 将加密结果输出为Base64编码
const base64Encoded = CryptoJS.enc.Base64.stringify(hash);
// 输出结果
console.log("SHA256: " + base64Encoded);

// 场景二:HMAC-SHA256加密,输出Base64
// 定义要加密的消息和密钥
const message = "Hello, World!";
const secretKey = "MySecretKey";
// 使用HMAC-SHA256算法进行加密
const hash = CryptoJS.HmacSHA256(message, secretKey);
// 将加密结果输出为Base64编码
const base64Encoded = CryptoJS.enc.Base64.stringify(hash);
// 输出结果
console.log("HMAC-SHA256: " + base64Encoded);

// 场景三: 字符串编码为Base64
// 定义要编码的字符串
const message = "Hello, World!";
// 使用Base64编码
const base64Encoded = btoa(message)
// 输出结果
console.log("Base64: " + base64Encoded);

非内置的 JS 类库

使用 fox.liveRequire 方法可以动态地引入从 npm 上发布的其他纯 JavaScript 库,以扩展 Apifox 的功能。请注意,仅支持在浏览器端运行的库,并且不支持带有 C/C++ 等语言扩展的库。如果尝试加载此类库,可能会导致运行超时或产生异常。为了最好的运行效果,请选择明确支持浏览器端运行的库,并仅引入纯 JavaScript 库。

注意
  1. 仅 Apifox 版本号 >= 1.4.5 才支持,老版本不支持,请升级到最新版。
  2. 非内置库需要动态从网络下载 JS 类库,所以必须要联网,且性能有有所损耗,建议优先使用内置的 JS 库。
  3. WEB 版不支持该方式,请使用 Apifox 桌面客户端。

示例代码如下:

// 使用非内置的 JS 类库示例

// 引入单个 npm 库:md5
fox.liveRequire("md5", (md5) => {
try {
console.log(md5("message")); // => '04a410d39d39f9831217edd702d7fde0'
} catch (error) {
console.error("An error occurred during liveRequire callback", error);
throw error;
}
});

// 引入多个 npm 库:camelize,md5
fox.liveRequire(["camelize", "md5"], ([camelize, md5]) => {
try {
console.log("loaded module is ", camelize, md5);

console.log('camelize("foo-bar") is ', camelize("foo-bar")); // => 'fooBar'
console.log('md5("message") is ', md5("message")); // => '04a410d39d39f9831217edd702d7fde0'
} catch (error) {
console.error("An error occurred during liveRequire callback", error);
throw error;
}
});

// 引入多个 npm 库(带版本):camelcase,md5
fox.liveRequire(
[
{
name: "camelcase",
version: "6.2.1",
},
"md5",
],
([camelCase, md5]) => {
try {
console.log("loaded module is ", camelCase, md5);

console.log('camelCase("foo-bar") is ', camelCase("foo-bar")); // => 'fooBar'
console.log('md5("message") is ', md5("message")); // => '04a410d39d39f9831217edd702d7fde0'
} catch (error) {
console.error("An error occurred during liveRequire callback", error);
throw error;
}
}
);