第2章 Express 基础(二)

4 中间件简介

中间件是 Express 应用程序中执行的函数。每个中间件函数可以处理请求和响应对象,并决定是否将控制权交给下一个中间件。

中间件基本示例:

// 一个简单的日志中间件
app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next(); // 将控制权交给下一个中间件
});

// 定义一个处理 GET 请求的路由
app.get('/', (req, res) => {
    res.send('Hello, world!');
});

// 启动服务器
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

在这里插入图片描述

代码详解:

  • app.use((req, res, next) => {...});:定义一个全局中间件,记录每个请求的方法和 URL,并调用 next() 将控制权交给下一个中间件或路由处理程序。
  • 中间件的执行顺序与它们在代码中的定义顺序相同。
5 内置中间件

Express 提供了一些内置中间件,用于处理常见任务,例如解析 JSON 请求体和提供静态文件服务。

解析 JSON 请求体:

// 解析 JSON 请求体中间件
app.use(express.json());

app.post('/data', (req, res) => {
    // 访问请求体中的数据
    const data = req.body;
    res.send(`Received data: ${JSON.stringify(data)}`);
});

// 启动服务器
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

提供静态文件服务:

// 提供 public 目录下的静态文件
app.use(express.static('public'));

// 启动服务器
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

将静态文件(例如 HTML、CSS 和 JavaScript 文件)放在 public 目录下,可以通过 http://localhost:3000/filename 访问。
如在public 下面放入index.html文件,内容如下:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    Index.html
  </body>
</html>

在这里插入图片描述

6 自定义中间件

你可以创建自己的中间件来实现特定功能。例如,一个简单的请求日志中间件可以记录请求的时间戳和路径。

示例:

// 自定义日志中间件
const requestLogger = (req, res, next) => {
    const timestamp = new Date().toISOString();
    console.log(`[${timestamp}] ${req.method} ${req.url}`);
    next();
};

// 使用自定义中间件
app.use(requestLogger);

// 定义一个处理 GET 请求的路由
app.get('/', (req, res) => {
    res.send('Hello, world!');
});

// 启动服务器
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

代码详解:

  • 自定义中间件 requestLogger 记录每个请求的时间戳、方法和 URL。
  • requestLogger 中间件添加到应用程序中,使其在每个请求时执行。
7 模板引擎入门

模板引擎允许我们在服务器端生成动态 HTML 页面。Express 支持多种模板引擎,如 EJS、Pug 和 Handlebars。

示例(使用 EJS):

首先安装 EJS:

npm install ejs --save

配置 Express 使用 EJS 作为模板引擎:

// 设置 EJS 为模板引擎
app.set('view engine', 'ejs');

// 定义一个路由渲染 EJS 模板
app.get('/hello', (req, res) => {
    res.render('hello', { name: 'Express' });
});

// 启动服务器
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

在项目的 views 目录下创建一个名为 hello.ejs 的文件:

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Hello, <%= name %>!</h1>
</body>
</html>

代码详解:

  • app.set('view engine', 'ejs');:配置 Express 使用 EJS 作为模板引擎。
  • res.render('hello', { name: 'Express' });:渲染 views 目录下的 hello.ejs 模板,并传递数据 { name: 'Express' }
    在这里插入图片描述

通过本章内容,读者应该能够理解并掌握 Express 的基本用法,包括路由的定义和使用、中间件的应用、模板引擎的集成以及静态文件服务的提供。在接下来的章节中,我们将探讨 Express 的高级功能和实践技巧。

  • 15
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值