路由中间件使用

  • 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 已经启动~~~')
})


posted @ 2023-01-04 09:46  码农阿亮  阅读(44)  评论(0)    收藏  举报