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

在本教程中,我将演示如何在 NodeJS 中使用 techblik.com API。

为了演示这一点,我们将构建一个简单的脚本,在执行时打印出 Google 搜索服务器的 IP 地址。 此脚本将使用 techblik.com 的 API 的 DNS 记录端点。

为了构建它,我们将使用三种方法,第一种使用 NodeJS 中内置的 https 模块。 第二个将使用 node-fetch 模块。 然后最后将使用 axios 客户端库。

什么是 techblik.com API?

techblik.com 是一个提供工具、API 和资源来创建、管理和发展在线业务的网站。 这些工具中包含一个 API,可用于管理网站的性能、安全性和审核网站问题。 API 有一个慷慨的免费层,您可以利用它。

先决条件

要学习本教程,您需要了解 JavaScript,包括 Promise 和 ES6 语法。 至于软件,你应该安装 NodeJS 和一个文本编辑器,比如 Visual Studio Code。

发出请求时,您将需要一个 techblik.com 帐户来获取用于身份验证的 API 密钥。 要获得一个,请前往 API 登录页面并创建一个免费帐户。

创建帐户后,您应该被重定向到仪表板,您可以在其中找到您的 API 密钥。

建设项目

首先,创建一个项目文件夹并使用您选择的终端打开它,然后运行以下命令。

npm init -y

上述命令会将项目目录初始化为 NodeJS 项目。

接下来,运行下面的命令,这将为我们的项目安装所有依赖项

npm install dotenv axios node-fetch

依赖安装成功后,在项目根目录下创建三个脚本 vanilla.js、with-axios.js、with-fetch.js 和一个 .env 文件来存储我们的环境变量。

最后,项目根目录应如下所示:

接下来,打开 .env 文件并使用以下代码行添加您的 techblik.com API 密钥:

API_KEY=<api key>

替换为您的实际 API 密钥。

使用 Vanilla.js

NodeJS 有一个内置的 http 和 https 模块,我们可以使用它来发出客户端请求。 我们将首先使用这种方法。

打开 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.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.com",
  path: "/dnsrecord",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-api-key": apiKey,
  },
};

现在我们可以继续调用传入 options 方法的请求函数:

const req = request(options, response => {

  // we are going to add response handlers here

});

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

  如何在谷歌浏览器中阻止网站

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

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 响应,因为它会流回给我们。

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

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

最后,我们将侦听错误并将它们记录到控制台(如果它们出现)。

因此对请求函数的调用应该是这样的

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.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 等客户端库将帮助您创建相同的程序,但代码更清晰、更简洁。

  个人或企业的 10 个最佳工作流程自动化和集成平台

使用节点获取

要使用 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() {
  // The function body will go here
}

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

const response = await fetch("https://api.techblik.com.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.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。 首先,让我们导入 dotenv 和 axios 包。

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

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

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

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

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

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

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

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

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

最后,让我们调用我们之前导入的 post 函数,传入我们之前定义的 url、data 和 options 变量作为参数。 因为这将返回一个承诺,所以您可以在最终返回时使用 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.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 中使用它。

  易趣安全吗? 15 个 eBay 骗局以及如何避免它们

所有其他端点都可以以类似的方式使用; 所有改变的是端点和您必须作为请求正文的一部分发送的参数。 API 的文档可以在这里找到。