当前位置:网站首页>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
边栏推荐
- Who will answer the question?
- [AI vision · quick review of NLP natural language processing papers today, issue 29] Mon, 14 Feb 2022
- [AI vision · quick review of NLP natural language processing papers today, issue 30] Thu, 14 APR 2022
- The whole process of connecting the newly created unbutu system virtual machine with xshell and xftp
- Detailed explanation on the use of annotation tool via (VGg image annotator) in mask RCNN
- VS Studio 修改C语言scanf等报错
- ROS series (IV): ROS communication mechanism series (6): parameter server operation
- The super large image labels in remote sensing data set are cut into specified sizes and saved into coco data set - target detection
- ROS series (IV): ROS communication mechanism series (2): Service Communication
- Photoshop installation under win10
猜你喜欢

作为一名码农,女友比自己更能码是一种什么体验?

标识符、关键字、数据类型

創下國產手機在海外市場銷量最高紀錄的小米,重新關注國內市場

Writing latex with vscode - the latest tutorial 2022 / 4 / 17

Let matlab2018b support the mex configuration of vs2019

Openvino only supports Intel CPUs of generation 6 and above

Xiaomi, which has set the highest sales record of domestic mobile phones in overseas markets, paid renewed attention to the domestic market

Identificateur, mot - clé, type de données

【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..

51 single chip microcomputer: D / a digital to analog conversion experiment
随机推荐
How Zotero quotes in word jump to references / hyperlink
Concepts of objects and classes
Design and implementation of redis (4): what is the event driver of redis
[Li Hongyi 2022 machine learning spring] hw6_ Gan (don't understand...)
Basic knowledge of convolutional neural network
一个函数秒杀2Sum 3Sum 4Sum问题
对象和类的概念
Nel ASA: her ø Ya facility in Norway officially opened
使用大华设备开发行AI人流量统计出现时间不正确的原因分析
【NeurIPS 2019】Self-Supervised Deep Learning on Point Clouds by Reconstructing Space
MySQL zip installation tutorial
Websites frequented by old programmers (continuously updated)
Notes sur l'apprentissage profond (Ⅱ) - - Principe et mise en oeuvre de la fonction d'activation
Summary of knowledge map (3)
Key point detection of human hand based on mediapipe
【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..
Cause analysis of incorrect time of AI traffic statistics of Dahua Equipment Development Bank
ERROR: Could not find a version that satisfies the requirement win32gui
[AI vision · quick review of robot papers today, issue 29] Mon, 14 Feb 2022
ROS series (IV): ROS communication mechanism series (3): parameter server