如何在 Deno 中使用 Express
Express 是一个流行的 Web 框架,以其简洁、不带偏见以及拥有庞大中间件生态系统而闻名。
本操作指南将向您展示如何使用 Express 和 Deno 创建一个简单的 API。
初始化一个新的 Deno 项目 跳至标题
在命令行中运行命令创建一个新的启动项目,然后进入项目目录
deno init my-express-project
cd my-express-project
安装 Express 跳至标题
要安装 Express,我们将使用 npm:
模块说明符。此说明符允许我们从 npm 导入模块
deno add npm:express
这会将最新的 express
包添加到 deno.json
文件中的 imports
字段。现在您可以使用 import express from "express";
在代码中导入 express
了。
更新 main.ts
跳至标题
在 main.ts
中,让我们创建一个简单的服务器
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Welcome to the Dinosaur API!");
});
app.listen(8000);
console.log(`Server is running on http://localhost:8000`);
您可能会注意到编辑器正在抱怨 req
和 res
参数。这是因为 Deno 没有 express
模块的类型。要解决此问题,您可以直接从 npm 导入 Express 类型文件。在 main.ts
文件的顶部添加以下注释
// @ts-types="npm:@types/express@4.17.15"
此注释告诉 Deno 使用来自 @types/express
包的类型。
运行服务器 跳至标题
当您初始化项目时,Deno 设置了一个任务来运行 main.ts 文件,您可以在 deno.json
文件中看到它。更新 dev
任务以包含 --allow-net
标志
{
"scripts": {
"dev": "deno run --allow-net main.ts"
},
...
}
This will allow the project to make network requests. You can [read more about permissions flags](/runtime/fundamentals/security/).
Now you can run the server with:
```sh
deno run dev
如果您在浏览器中访问 localhost:8000
,您应该会看到
欢迎来到恐龙 API!
添加数据和路由 跳至标题
下一步是添加一些数据。我们将使用从这篇文章中找到的恐龙数据。您可以随意从这里复制。
在项目根目录中创建一个 data.json
文件,并粘贴恐龙数据。
接下来,我们将把这些数据导入到 main.ts
中
import data from "./data.json" with { 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);
console.log(`Server is running on http://localhost:8000`);
让我们用 deno run dev
运行服务器,并在浏览器中访问 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."
},
...
您还可以通过访问 "/api/恐龙名称" 获取特定恐龙的详细信息,例如 localhost:8000/api/aardonyx
将显示
{
"name": "Aardonyx",
"description": "An early stage in the evolution of sauropods."
}
🦕 现在您已经准备好在 Deno 中使用 Express 了。您可以考虑将此示例扩展为一个恐龙 Web 应用程序。或者查看Deno 内置的 HTTP 服务器。