一、中间件的分类
Express 官方把常见的中间件用法,分成了 5 大类:
应用级别的中间件
路由级别的中间件
错误级别的中间件
Express 内置的中间件
第三方的中间件
二、应用级别的中间件
通过 app.use() 或 app.get() 或 app.post() ,绑定到 app 实例上的中间件,叫做应用级别的中间件
局部中间件也属于应用级别的
const express = require("express")
const req = require("express/lib/request")
const res = require("express/lib/response")
const app = express()
app.use((req,res,next) => {
next()
})
app.get('/',(req,res) => {
res.send("Home Page")
})
app.listen(81, () => {
console.log('http://127.0.0.1')
})
![Node-14-Express-中间件的分类_第1张图片](http://img.e-com-net.com/image/info8/54009e08a87b466b80a52d9b32d5e1bc.jpg)
三、路由级别的中间件
绑定到 express.Router() 实例上的中间件,叫做路由级别的中间件。它的用法和应用级别中间件没有任何区别。只不过,应用级别中间件是绑定到 app 实例上,路由级别中间件绑定到 router 实例上.
代码可以参考之前:https://editor.csdn.net/md/?articleId=124325770
四、错误级别的中间件
错误级别中间件的作用:专门用来捕获整个项目中发生的异常错误,从而防止项目异常崩溃的问题。
格式:错误级别中间件的 function 处理函数中,必须有 4 个形参,形参顺序从前到后,分别是 (err, req, res, next)。
错误级别的中间件,
必须注册在所有路由之后!
const express = require('express')
const app = express()
app.get('/', (req, res) => {
throw new Error('服务器内部发生了错误!')
res.send('Home page.')
})
app.use((err, req, res, next) => {
console.log('发生了错误!' + err.message)
res.send('Error:' + err.message)
})
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
五、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+ 版本中可用)
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.post('/user', (req, res) => {
console.log(req.body)
res.send('ok')
})
app.post('/book', (req, res) => {
console.log(req.body)
res.send('ok')
})
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
六、第三方的中间件
非 Express 官方内置的,而是由第三方开发出来的中间件,叫做第三方中间件。在项目中,可以按需下载并配置第三方中间件,从而提高项目的开发效率。
在 express@4.16.0 之前的版本中,经常使用 body-parser 这个第三方中间件,来解析请求体数据。使用步
骤如下:
运行 npm install body-parser 安装中间件
使用 require 导入中间件
调用 app.use() 注册并使用中间件
const express = require('express')
const app = express()
const parser = require('body-parser')
app.use(parser.urlencoded({ extended: false }))
app.post('/user', (req, res) => {
console.log(req.body)
res.send('ok')
})
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
七、项目地址: https://github.com/Mbm7280/node-learning