跳到主要内容
本页内容

如何在 Deno 中使用 Express

Express 是一个流行的 Web 框架,以简单、非侵入式以及庞大的中间件生态系统而闻名。

本指南将向您展示如何使用 Express 和 Deno 创建一个简单的 API。

查看源代码。

创建 main.ts 跳转到标题

让我们创建 main.ts

touch main.ts

main.ts 中,让我们创建一个简单的服务器

// @deno-types="npm:@types/[email protected]"
import express from "npm:[email protected]";

const app = express();

app.get("/", (req, res) => {
  res.send("Welcome to the Dinosaur API!");
});

app.listen(8000);

让我们运行这个服务器

deno run -A main.ts

并将浏览器指向 localhost:8000。您应该会看到

欢迎使用恐龙 API!

添加数据和路由 跳转到标题

下一步是添加一些数据。我们将使用从 这篇文章 中找到的恐龙数据。您可以 从这里复制

让我们创建 data.json

touch data.json

并将恐龙数据粘贴进去。

接下来,让我们将该数据导入到 main.ts。让我们在文件顶部添加以下行

import data from "./data.json" assert { type: "json" };

然后,我们可以创建访问该数据的路由。为了保持简单,我们只为 /api//api/:dinosaur 定义 GET 处理程序。在 const app = express(); 行之后添加以下代码

app.get("/", (req, res) => {
  res.send("Welcome to the Dinosaur API!");
});

app.get("/api", (req, res) => {
  res.send(data);
});

app.get("/api/:dinosaur", (req, res) => {
  if (req?.params?.dinosaur) {
    const found = data.find((item) =>
      item.name.toLowerCase() === req.params.dinosaur.toLowerCase()
    );
    if (found) {
      res.send(found);
    } else {
      res.send("No dinosaurs found.");
    }
  }
});

app.listen(8000);

让我们使用 deno run -A main.ts 运行服务器,并查看 localhost:8000/api。您应该会看到恐龙列表

[
  {
    "name": "Aardonyx",
    "description": "An early stage in the evolution of sauropods."
  },
  {
    "name": "Abelisaurus",
    "description": "\"Abel's lizard\" has been reconstructed from a single skull."
  },
  {
    "name": "Abrictosaurus",
    "description": "An early relative of Heterodontosaurus."
  },
...

当我们转到 localhost:8000/api/aardonyx

{
  "name": "Aardonyx",
  "description": "An early stage in the evolution of sauropods."
}

太棒了!