如何在 JavaScript (NodeJS) 中使用 techblik.com API

探索在 NodeJS 中使用 techblik.com API 的多种方法

本教程将详细介绍如何在 NodeJS 环境中利用 techblik.com API。我们将通过构建一个简单的脚本来演示其功能,该脚本在运行时会检索并显示 Google 搜索服务器的 IP 地址。这个过程将使用 techblik.com API 提供的 DNS 记录接口。

为了实现这一目标,我们将探讨三种不同的方法:第一种方法将直接使用 NodeJS 内置的 https 模块;第二种方法将采用 node-fetch 模块,这是一个更现代的替代方案;最后,我们将使用 axios 客户端库,它提供了一个更高级和用户友好的 API 请求方式。

什么是 techblik.com API?

techblik.com 是一个综合性的平台,提供一系列工具、API 和资源,旨在帮助用户构建、管理和发展在线业务。其提供的工具中就包括一个 API,可用于监控网站的性能、增强安全性以及解决网站存在的问题。值得一提的是,该 API 提供了一个慷慨的免费层级,方便用户体验和探索其功能。

前期准备

要充分理解本教程,您需要具备一定的 JavaScript 基础,包括对 Promise 和 ES6 语法的理解。在软件方面,请确保您已安装 NodeJS 和一个文本编辑器,例如 Visual Studio Code。此外,您还需要一个 techblik.com 帐户来获取 API 密钥,该密钥将用于身份验证。您可以在 API 登录页面创建免费帐户。

成功创建帐户后,您将被重定向到仪表板,在那里您可以找到您的 API 密钥,请妥善保管此密钥。

项目构建

首先,创建一个新的项目文件夹,并使用您偏好的终端进入该文件夹。然后,执行以下命令以初始化一个新的 NodeJS 项目:

npm init -y

此命令将当前项目目录初始化为一个 NodeJS 项目。

接下来,运行以下命令以安装项目所需的依赖项:

npm install dotenv axios node-fetch

安装完成后,在项目根目录下创建三个脚本文件:vanilla.jswith-axios.jswith-fetch.js,以及一个 .env 文件用于存储环境变量。

完成上述步骤后,您的项目目录结构应如下所示:

现在,打开 .env 文件,并添加您的 techblik.com API 密钥,如下所示:

API_KEY=<api key>

请将 <api key> 替换为您真实的 API 密钥。

使用 Vanilla.js

NodeJS 内置了 httphttps 模块,我们可以使用它们来发起客户端请求。我们将从使用这种方法开始。

打开 vanilla.js 文件,并在文件顶部添加以下代码行,导入所需的依赖项:

import { request } from "https";
import { config } from "dotenv";

接下来,我们将调用 config() 函数来加载环境变量。然后,我们将 API 密钥和目标主机名分别存储在变量中:

config();

const apiKey = process.env.API_KEY;
const host="google.com";

当我们在 NodeJS 中调用 request 函数来发起 HTTP 请求时,我们需要提供一些选项,例如我们想要连接的主机和端点、将要使用的 HTTP 方法以及请求的标头。因此,我们将创建一个变量来存储这些选项:

const options = {
  hostname: "api.techblik.com",
  path: "/dnsrecord",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-api-key": apiKey,
  },
};

到目前为止,vanilla.js 文件中的代码应该如下所示:

import { request } from "https";
import { config } from "dotenv";

config();

const apiKey = process.env.API_KEY;
const host="google.com"

const options = {
  hostname: "api.techblik.com",
  path: "/dnsrecord",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-api-key": apiKey,
  },
};

现在,我们可以继续调用 request 函数,传入之前定义的 options 对象:

const req = request(options, response => {

  // 我们将在这里添加响应处理程序

});

正如您所见,request 函数接受两个参数。第一个是之前定义的选项对象,第二个是一个回调函数,它将处理来自服务器的响应。在此回调函数中,我们可以添加事件监听器,以便在服务器发送数据、完成数据发送或发送错误时进行处理。

为了添加不同的响应处理程序,请在回调函数中添加以下代码行:

let data = "";

response.on("data", chunk => {
  data += chunk;
});

response.on("end", () => {
  console.log(JSON.parse(data).data.A);
});

response.on("error", error => {
  console.log(error);
});

data 变量只是一个字符串,我们将在此存储服务器的 JSON 响应,因为它会流式返回给我们。

为了实际存储数据,我们将监听响应对象的 data 事件。每当触发此事件时,我们都会将服务器发送的数据块追加到 data 变量中。

然后,为了最终使用数据,我们将在响应对象上监听 end 事件。当服务器发送完所有数据并结束响应时,将调用此方法。

最后,我们将侦听 error 事件,并将错误记录到控制台(如果它们发生)。

因此,对 request 函数的调用应该是这样的:

const req = request(options, response => {

  let data = "";

  response.on("data", chunk => {
    data += chunk;
  });

  response.on("end", () => {
    console.log(JSON.parse(data).data.A);
  });

  response.on("error", error => {
    console.log(error);
  });

});

最后,我们需要将一些数据写入请求体并结束请求:

req.write(JSON.stringify({ url: host, types: ["A"] }));
req.end();

最后,该文件应如下所示:

import { request } from "https";
import { config } from "dotenv";

config();

const apiKey = process.env.API_KEY;
const host="google.com"

const options = {
  hostname: "api.techblik.com",
  path: "/dnsrecord",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-api-key": apiKey,
  },
};

const req = request(options, response => {

  let data = "";

  response.on("data", chunk => {
    data += chunk;
  });

  response.on("end", () => {
    console.log(JSON.parse(data).data.A);
  });

  response.on("error", error => {
    console.log(error);
  });

});

req.write(JSON.stringify({ url: host, types: ["A"] }));
req.end();

现在,如果您返回终端并使用 node vanilla.js 命令运行脚本,您应该会得到以下输出:

[
  { address: '172.253.122.101', ttl: 247 },
  { address: '172.253.122.113', ttl: 247 },
  { address: '172.253.122.100', ttl: 247 },
  { address: '172.253.122.102', ttl: 247 },
  { address: '172.253.122.138', ttl: 247 },
  { address: '172.253.122.139', ttl: 247 }
]

这就是第一部分。使用内置 HTTP/S 模块的明显缺点是代码冗长。像 node-fetch 这样的客户端库可以帮助您创建相同的程序,但代码更加简洁明了。

使用 node-fetch

要使用 node-fetch 创建相同的脚本,请打开 with-fetch.js 文件,并在顶部添加以下导入:

import fetch from "node-fetch";
import { config } from "dotenv";

然后,调用 config 函数配置环境变量,并为 API_KEY 和我们将要请求其 A 记录的主机设置常量:

config();

const apiKey = process.env.API_KEY;
const host="google.com";

接下来,我们将定义一个函数来进行 API 调用。此函数将是异步的:

async function request() {
  // 函数体将在此处
}

在函数体内,我们需要调用之前从 node-fetch 包中导入的 fetch 函数:

const response = await fetch("https://api.techblik.com/dnsrecord", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": apiKey,
    },
    body: JSON.stringify({ url: host, types: ["A"] }),
});

然后在调用 fetch 函数之后,我们想要解析我们的响应并处理可能出现的任何错误:

if (response.ok) {
    const { data } = await response.json();

    console.log(data.A);
  } else {
    console.log(response);
  }

此时,在其请求之后添加对该函数的调用:

request();

您的文件现在应如下所示:

import fetch from "node-fetch";
import { config } from "dotenv";

config();

const apiKey = process.env.API_KEY;
const host = "google.com";

async function request() {
  const response = await fetch("https://api.techblik.com/dnsrecord", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": apiKey,
    },
    body: JSON.stringify({ url: host, types: ["A"] }),
  });

  if (response.ok) {
    const { data } = await response.json();

    console.log(data.A);
  } else {
    console.log(response);
  }
}

request();

使用 node with-fetch.js 运行该脚本应该会产生以下输出:

[
  { address: '172.253.122.113', ttl: 134 },
  { address: '172.253.122.138', ttl: 134 },
  { address: '172.253.122.100', ttl: 134 },
  { address: '172.253.122.139', ttl: 134 },
  { address: '172.253.122.102', ttl: 134 },
  { address: '172.253.122.101', ttl: 134 }
]

使用 Axios

最后,我们将使用 Axios 访问 techblik.com API。首先,让我们导入 dotenvaxios 包:

import axios from "axios";
import { config } from "dotenv";

接下来,让我们调用 config 函数来设置环境变量。此外,让我们将主机名和 API 密钥存储在单独的常量中:

config();
const host = "google.com";
const key = process.env.API_KEY;

现在,让我们将 API 端点的 URL 存储在另一个常量中:

const url = "https://api.techblik.com/dnsrecord";

接下来,让我们将作为请求正文一部分发送的数据存储在另一个常量中:

const data = { url: host, types: ["A"] };

然后在发送请求之前要做的最后一件事是将元选项(例如标头)存储在另一个常量中:

const options = {
  headers: {
    "Content-Type": "application/json",
    "x-api-key": key,
  },
};

最后,让我们调用我们之前导入的 post 函数,传入我们之前定义的 urldataoptions 变量作为参数。因为它将返回一个 Promise,所以您可以在最终返回时使用 then 来处理响应:

axios.post(url, data, options).then(({ data }) => {
  console.log(data.data.A);
});

最后,with-axios 文件中的代码应如下所示:

import axios from "axios";
import { config } from "dotenv";

config();
const host = "google.com";
const key = process.env.API_KEY;

const url = "https://api.techblik.com/dnsrecord";
const data = { url: host, types: ["A"] };
const options = {
  headers: {
    "Content-Type": "application/json",
    "x-api-key": key,
  },
};

axios.post(url, data, options).then(({ data }) => {
  console.log(data.data.A);
});

当您使用 node with-axios.js 运行脚本时,它应该显示以下输出:

[
  { address: '142.251.163.138', ttl: 60 },
  { address: '142.251.163.113', ttl: 60 },
  { address: '142.251.163.100', ttl: 60 },
  { address: '142.251.163.101', ttl: 60 },
  { address: '142.251.163.102', ttl: 60 },
  { address: '142.251.163.139', ttl: 60 }
]

总结

在本文中,我们使用三种不同的方法创建了相同的脚本。这样做的目的是为了强调使用 techblik.com API 是多么容易,以及我们如何在 JavaScript,特别是 NodeJS 中使用它。所有其他端点都可以以类似的方式使用;所有改变的是端点和您必须作为请求正文一部分发送的参数。您可以在 这里找到 API 的文档。