deno.com
本页内容

如何将 Express 与 Deno 一起使用

Express 是一个流行的 Web 框架,以其简单和非主观性以及庞大的中间件生态系统而闻名。

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

在此处查看源代码。

创建 main.ts 跳转到标题

让我们创建 main.ts

touch main.ts

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

// @ts-types="npm:@types/express@4.17.15"
import express from "npm:express@4.18.2";

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."
}

太棒了!

您找到所需的内容了吗?

隐私政策