当前位置:网站首页>Express中间件②(中间件的分类)
Express中间件②(中间件的分类)
2022-04-23 03:53:00 【十八岁讨厌编程】
文章目录
中间件的分类
为了方便大家理解和记忆中间件的使用,Express 官方把常见的中间件用法,分成了 5 大类,分别是:
① 应用级别的中间件
② 路由级别的中间件
③ 错误级别的中间件
④ Express 内置的中间件
⑤ 第三方的中间件
应用级别的中间件
通过 app.use() 或 app.get() 或 app.post() ,绑定到 app 实例上的中间件,叫做应用级别的中间件,代码示例如下:
路由级别的中间件
绑定到 express.Router() 实例上的中间件,叫做路由级别的中间件。它的用法和应用级别中间件没有任何区别。只不过,应用级别中间件是绑定到 app 实例上,路由级别中间件绑定到 router 实例上,代码示例如下:
错误级别的中间件
错误级别中间件的作用:专门用来捕获整个项目中发生的异常错误,从而防止项目异常崩溃的问题。
格式:错误级别中间件的 function 处理函数中,必须有 4 个形参,形参顺序从前到后,分别是 (err, req, res, next)。
注意:错误级别的中间件,必须注册在所有路由之后!
因为按照从前往后的执行顺序,如果把错误级别的中间件放在前面,当发生了错误后,程序往后执行是没有处理代码的。
Express内置的中间件
自 Express 4.16.0 版本开始,Express 内置了 3 个常用的中间件,极大的提高了Express 项目的开发效率和体验:
① express.static 快速托管静态资源的内置中间件,例如: HTML 文件、图片、CSS 样式等(无兼容性)
② express.json 解析 JSON 格式的请求体数据(有兼容性,仅在 4.16.0+ 版本中可用)
③ express.urlencoded 解析 URL-encoded 格式的请求体数据(有兼容性,仅在 4.16.0+ 版本中可用)
使用示例:
express.json的使用示例
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 注意:除了错误级别的中间件,其他的中间件,必须在路由之前进行配置
// 通过 express.json() 这个中间件,解析表单中的 JSON 格式的数据
app.use(express.json())
app.post('/user', (req, res) => {
// 在服务器,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
// 默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body)
res.send('ok')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
注意:在服务器端,可以通过 req,body 来获取 JSON 格式的表单数据和 url-encoded 格式的数据
默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
express.urlencoded使用示例
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 注意:除了错误级别的中间件,其他的中间件,必须在路由之前进行配置
// 通过 express.urlencoded() 这个中间件,来解析 表单中的 url-encoded 格式的数据
app.use(express.urlencoded({
extended: false }))
app.post('/book', (req, res) => {
// 在服务器,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
// 默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
// 在服务器端,可以通过 req,body 来获取 JSON 格式的表单数据和 url-encoded 格式的数据
console.log(req.body)
res.send('ok')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
第三方的中间件
非 Express 官方内置的,而是由第三方开发出来的中间件,叫做第三方中间件。在项目中,大家可以按需下载并配置第三方中间件,从而提高项目的开发效率。
例如:在 [email protected] 之前的版本中,经常使用 body-parser 这个第三方中间件,来解析请求体数据。使用步骤如下:
- 运行 npm install body-parser 安装中间件
- 使用 require 导入中间件
- 调用 app.use() 注册并使用中间件
注意:Express 内置的 express.urlencoded 中间件,就是基于 body-parser 这个第三方中间件进一步封装出来的。
(这也就说明了两者的注册语法为什么这么相似的原因)
使用代码:
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 导入解析表单数据的中间件 body-parser
const parser = require('body-parser')
// 2. 使用 app.use() 注册中间件
app.use(parser.urlencoded({
extended: false }))
// app.use(express.urlencoded({ extended: false }))
app.post('/user', (req, res) => {
// 如果没有配置任何解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body)
res.send('ok')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
版权声明
本文为[十八岁讨厌编程]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zyb18507175502/article/details/124354166
边栏推荐
- The art of concurrent programming (6): explain the principle of reentrantlock in detail
- Network principle | connection management mechanism in TCP / IP important protocol and core mechanism
- UDP协议与TCP协议
- 使用大华设备开发行AI人流量统计出现时间不正确的原因分析
- Vs studio modifies C language scanf and other errors
- The latest price trend chart and trading points of London Silver
- Common net HP UNIX system FTP server listfiles returns null solution.
- 【NeurIPS 2019】Self-Supervised Deep Learning on Point Clouds by Reconstructing Space
- Summary of knowledge map (I)
- Create virtual machine
猜你喜欢
Create virtual machine
Wechat applet cloud database value assignment to array error
Opencv4 QR code recognition test
ROS series (I): rapid installation of ROS
The great gods in acmer like mathematics very much
[AI vision · quick review of robot papers today, issue 28] wed, 1 Dec 2021
Second kill all interval related problems
Design and implementation of redis (1): understand data structures and objects
Xiaomi, which has set the highest sales record of domestic mobile phones in overseas markets, paid renewed attention to the domestic market
Instructions for fastmock
随机推荐
Counting and sorting (C language implementation) -- learning notes
网络原理 | TCP/IP中的连接管理机制 重要协议与核心机制
The art of concurrent programming (5): the use of reentrantlock
Xshell、Xftp连接新创建的Unbutu系统虚拟机全流程
Digital image processing third edition Gonzalez notes Chapter 2
PolarMask is not in the models registry
Leetcode punch in diary day 01
Using VBA interval to extract one column from another in Excel
Concepts of objects and classes
MySQL is completely uninstalled and MySQL service is cleaned up
How to introduce opencv into cmake project
Wechat applet cloud database value assignment to array error
The super large image labels in remote sensing data set are cut into specified sizes and saved into coco data set - target detection
Design and implementation of redis (6): how redis achieves high availability
Identifier, keyword, data type
Process seven state transition diagram
Software testing process
Overview of knowledge map (II)
The art of concurrent programming (3): an in-depth understanding of the principle of synchronized
[mathematical modeling] my mathematical memory