通过 app.use() 、 app.get()、 app.post(),绑定到 app 实例上的中间件,叫做应用级别的中间件,
绑定到 express.Router() 实例上的中间件,叫做路由级别的中间件。
作用:捕获项目中的错误,防止项目因为错误崩溃
🌰 不使用错误级别中间件的情况:
// 导入Express
const express = require('express')
// 创建web服务器
const app = express()
// 监听get请求
app.get('/', (req, res) => {
throw new Error('出错啦❗️')
res.send('请求后响应的内容')
})
// 启动web服务器
app.listen(8080, () => {
console.log('✨服务已启动')
})

⭕️ 使用错误级别中间件:
// 导入Express
const express = require('express')
// 创建web服务器
const app = express()
// 监听get请求
app.get('/', (req, res) => {
throw new Error('出错啦❗️')
res.send('请求后响应的内容')
})
// 错误级别的中间件
app.use((err,req,res,next)=>{
res.send('错误信息:'+err.message+',但项目没有崩溃哟');
})
// 启动web服务器
app.listen(8080, () => {
console.log('✨服务已启动')
})

⚠️ 注意:错误级别中间件必须注册在所有路由之后
express.static 快速托管静态资源的内置中间件,例如:HTML 文件、图片、CSS 样式等(无兼容性问题)
express.json 解析 JSON 格式的请求体数据(仅在4.16.0+ 版本中可用)
express.urlencoded 解析 URL-encoded 格式的请求体数据(仅在4.16.0+ 版本中可用)
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));