路由中间件使用
- index.js
const express = require('express')
const app = express();
const mw = function (req,res,next){
console.log('这是第1个简单的中间函数');
//全局共享同一份req和res
const time =Date.now();
req.startTime =time;//将req对象上挂载自定义大属性,从而把时间共享给后面的所有路由
//把流转关系交给下一个中间件或者路由
//一定不要忘记调用next函数
next();
//为了防止逻辑混乱,Next调用后,不要再写其他的代码
}
const mw1 = function (req,res,next){
console.log('这是第1个局部中间函数');
next();
}
const mw2 = function (req,res,next){
console.log('这是第2个局部中间函数');
next();
}
const mw3 = function (req,res,next){
console.log('这是第3个局部中间函数');
next();
}
//将mw注册为全局生效的中间件,每个路由都会走,定义全局中间件,一定要在路由之前注册中间件
app.use(mw);
//定义"全局"中间件的简化形式
app.use((req,res,next) => {
console.log('这是第2个简单的中间件函数');
next();
});
//定义路由
app.get('/',(req,res) =>{
console.log('调用了/这个路由');
res.send('Home page.')
})
app.get('/getStartTime',(req,res) =>{
console.log('调用了/getStartTime这个路由');
res.send('getStartTime:' + req.startTime);
})
//局部中间件,可以连续调用多个中间件进行处理
app.get('/mw1',mw1,mw2,(req,res)=>{
res.send('局部中间件1')
})
app.get('/mw2',[mw1,mw2],(req,res)=>{
res.send('局部中间件2')
})
app.get('/mw3',mw3,(req,res)=>{
res.send('局部中间件2')
})
//内置中间件
app.use(express.static('public'));//托管public文件夹下的静态资源,http://127.0.0.1/img/tx1.png
app.use(express.json());//express.json() 解析表单中的json数据格式
app.use(express.urlencoded({extended:false}));//解析表单中的urlencoded格式的数据
app.post('/student',(req,res)=>{
console.log(req.body);//可以通过req.body来获取JSON格式的表单数据和url-encoded格式请求提数据
res.send('ok');
})
//错误中间件
//定义错误级别中间件,捕获整个项目的异常
app.use((err,req,res,next)=>{ //错误级别的中间件,必须注册在所有的路由之后
console.log('发生错误了!'+ err.message);
res.send('Error:' + err.message)
})
app.listen(80,()=>{
console.log('http:127.0.0.1 已经启动~~~')
})
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/17024020.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
