当前位置:网站首页>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
边栏推荐
- Design and implementation of redis (2): how to handle expired keys
- 一个函数秒杀2Sum 3Sum 4Sum问题
- 【李宏毅2022 机器学习春】hw6_GAN(不懂..)
- According to the category information and coordinate information of the XML file, the category area corresponding to the image is pulled out and stored in the folder.
- 什么是软件验收测试,第三方软件检测机构进行验收测试有什么好处?
- Vs Studio modifie le langage C scanf et d'autres erreurs
- Mechanical design knowledge point planning
- Key point detection of human hand based on mediapipe
- Using VBA interval to extract one column from another in Excel
- Three types of cyclic structure
猜你喜欢
[AI vision · quick review of today's sound acoustic papers issue 1] Thu, 14 APR 2022
標識符、關鍵字、數據類型
Abstract classes, interfaces and common keywords
The art of concurrent programming (2): synchronized usage scenarios
Seekbar custom style details
Add the compiled and installed Mysql to the path environment variable
The art of concurrent programming (3): an in-depth understanding of the principle of synchronized
A function second kill 2sum 3sum 4sum problem
ROS series (I): rapid installation of ROS
Xshell、Xftp连接新创建的Unbutu系统虚拟机全流程
随机推荐
Installation and configuration of MinGW under win10
Oracle JDK vs OpenJDK
The whole process of connecting the newly created unbutu system virtual machine with xshell and xftp
[AI vision · quick review of NLP natural language processing papers today, issue 28] wed, 1 Dec 2021
Design and implementation of redis (3): persistence strategy RDB, AOF
Design and implementation of redis (4): what is the event driver of redis
Network principle | connection management mechanism in TCP / IP important protocol and core mechanism
[AI vision · quick review of robot papers today, issue 28] wed, 1 Dec 2021
中国移动日赚2.85亿很高?其实是5G难带来更多利润,那么钱去哪里了?
Process seven state transition diagram
Design and implementation of redis (6): how redis achieves high availability
Let matlab2018b support the mex configuration of vs2019
Summary of knowledge map (3)
Common net HP UNIX system FTP server listfiles returns null solution.
【NeurIPS 2019】Self-Supervised Deep Learning on Point Clouds by Reconstructing Space
Does China Mobile earn 285 million a day? In fact, 5g is difficult to bring more profits, so where is the money?
Paddlepaddle model to onnx
vscode删除卸载残余
Machine translation baseline
Now is the best time to empower industrial visual inspection with AI