Express中间件

一、中间件的格式

  中间件函数的形参列表中,必须包含next参数。而路由处理函数中只包含req和res

const express = require('express')
const app = express()
app.get('/',(req,res,next()=>{
	next()
})
app.listen(80,()=>{})

二、中间件的分类

1、应用级别的中间件
  通过app.use()或app.get()或app.post(),绑定到app实例上的中间件叫做应该用级别的中间件

// 多个全局中间件
const express = require('express')
const app = express()
const port = 80

// 定义第一个全局中间件
app.use(function(req,res,next){
    console.log('第一个全局中间件');
    next();
})
// 定义第二个全局中间件
app.use(function(req,res,next){
    console.log('第二个全局中间件');
    next();
})
// 定义一个路由
app.get('/user', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
// 多个局部生效的中间件
const express = require('express')
const app = express()

// 1.定义中间件函数
const mw1 = (req,res,next)=>{
    console.log('调用了第一个局部生效的中间件');
    next()
}
const mw2 = (req,res,next)=>{
    console.log('调用了第二个局部生效的中间件');
    next()
}

// 2。创建路由
app.get('/',mw1,mw2,(req,res)=>{
    res.send('111')
})
app.get('/user',(req,res)=>{
    res.send('2222')
})
app.listen(80,()=>{
    console.log('http:127.0.0.1');
})

2、路由级别的中间件
  绑定到express.Router()实例上的中间件,叫做路由级别的中间件。应用级别的中间件是绑定到app实例上,路由级别中间件绑定到router实例上

// 这是路由模块
// 1.导入express
const express = require('express')
// 2.创建路由对象
const router = express.Router()

// 3.挂载具体的路由
router.get('/user/list',(req,res)=>{
    res.send('Get user list.')
})
router.post('/user/add',(req,res)=>{
    res.send('Add new user.')
})
// 4.向外导出路由对象
module.exports = router

3、错误级别的中间件

  • 作用:专门用来捕获整个项目中发生的异常错误,从而防止项目异常崩溃的问题
  • 格式:错误级别中间件的function处理函数中,必须有4个形参,形参顺序从前到后,分别是(err,req,res,next)
  • 注意:必须路由在前,中间件在后
const express = require('express')
const app = express()
const port = 80

// 1.定义路由
app.get('/',(req,res)=>{
    // 1.1人为制造错误
    throw new Error('服务器内部发生了错误!')
    res.send('Home page.')
})
// 2.定义错误级别的中间件,捕获整个项目中的异常错误,从而防止程序的崩溃
app.use((err,req,res,next)=>{
    console.log('发生了错误! '+err.message);
    res.send('Error :'+err.message)
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

4、Express内置的中间件

  • express.static 快速托管静态资源的内置中间件,例如:html文件,图片,CSS样式等(无兼容性)
  • express.json 解析json格式的请求体数据(有兼容性)
  • express.urlencoded 解析URL-encoded格式的请求提数据(有兼容性)
// 导入express模块
const express = require('express')
// 创建express的服务实例
const app= express()

// 注意:出了错误级别的中间件,其他的中间件,必须在路由之前进行配置
// 通过express.json()这个中间件,解析表单中的JSON格式的数据
app.use(express.json())
// 通过express.urlencoded()这个中间件,来解析表单中的url-encoded格式的数据
app.use(express.urlencoded({extended:false}))

app.post('/user',(req,res)=>{
    //在服务器,可以使用req.body这个属性,来接收客户端发过来的请求体数据
    //默认情况下,如果不配置解析表单数据的中间件,则req.body默认等于undefined
    console.log(req.body);
    res.send('ok')
})

app.post('/book',(req,res)=>{
    // 在服务器端,可以通过req.body来获取JSON格式的表单数据和url-encoded格式的数据
    console.log(req.body);
    res.send('okk')
})
// 调用app.listen方法,指定端口号并启动服务器
app.listen(80,(req,res)=>{
    console.log('http://127.0.0.1');
})

5、第三方的中间件
实现步骤:

  • 运行npm install body-parser安装中间件
  • 使用require导入中间件
  • 调用app.use()注册并使用中间件
// 导入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.post('/user',(req,res)=>{
    console.log(req.body);
    res.send('ok')
})

// 调用app.listen方法,指定端口号并启动服务器
app.listen(80,(req,res)=>{
    console.log('http://127.0.0.1');
})

6、自定义中间件
实现步骤:

  • 定义中间件
  • 监听req的data事件
  • 监听req的end事件
  • 使用querystring模块解析请求体数据
    • Node.js内置了一个querystring模块,专门用来处理查询字符串。通过这个模块提供的parse()函数,可以轻松把查询字符串解析成对象的格式
      在这里插入图片描述
  • 将自定义中间件封为模块
    在这里插入图片描述
    在这里插入图片描述
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值