» Node.js:使用Express构建REST API » 2. 开发 » 2.2 健康端点

健康端点

健康端点指服务器提供的特定端点或路由,用于确定服务器或应用程序的健康状态。该端点通常用于监控和管理目的,允许外部系统或监控工具通过其 API 检测系统否正常运行。

修改 src/app.ts

@@ -3,8 +3,8 @@ import express, { Request, Response } from "express";
 const app = express();
 const port = process.env.PORT || 3000;
 
-app.get("/ping", (req: Request, res: Response) => {
-  res.json({ message: "pong" });
+app.get("/", (req: Request, res: Response) => {
+  res.json({ status: "ok" });
 });
 
 app.listen(port, () => {

/ 端点的响应:

{"status":"ok"}

可选
如果想在健康端点的响应中包括 CPU 或内存数据,需要你在 Node.js 程序的运行环境中收集相关数据。

修改 src/app.ts [可选]:

@@ -1,10 +1,21 @@
 import express, { Request, Response } from "express";
+import os from "os";
 
 const app = express();
 const port = process.env.PORT || 3000;
 
-app.get("/ping", (req: Request, res: Response) => {
-  res.json({ message: "pong" });
+app.get("/", (req: Request, res: Response) => {
+  const cpuUsage = os.cpus();
+  const totalMemory = os.totalmem();
+  const freeMemory = os.freemem();
+  res.json({
+    status: "ok",
+    cpuUsage,
+    totalMemory,
+    totalMemory_MB: totalMemory / 1024 / 1024,
+    freeMemory,
+    freeMemory_MB: freeMemory / 1024 / 1024,
+  });
 });
 
 app.listen(port, () => {

其响应如下所示:

{
  "status": "ok",
  "cpuUsage": [
    {
      "model": "Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz",
      "speed": 2600,
      "times": {
        "user": 27721500,
        "nice": 0,
        "sys": 15033140,
        "idle": 188708050,
        "irq": 0
      }
    },
    {
      "model": "Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz",
      "speed": 2600,
      "times": {
        "user": 391930,
        "nice": 0,
        "sys": 406990,
        "idle": 231839750,
        "irq": 0
      }
    },
    ...
  ],
  "totalMemory": 17179869184,
  "totalMemory_MB": 16384,
  "freeMemory": 1339666432,
  "freeMemory_MB": 1277.60546875
}