中间件函数的形参列表中,必须包含next参数。而路由处理函数中只包含req和res
const express = require('express')
const app = express()
app.get('/',(req,res,next()=>{
next()
})
app.listen(80,()=>{})
s="token punctuation">,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、错误级别的中间件
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模块
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、第三方的中间件
实现步骤:
// 导入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、自定义中间件
实现步骤:
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
加入交流群
请使用微信扫一扫!