微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Express04:中间件

示例1(应用级)

/*
 中间件:处理过程的一个环节(本质上就是一个函数,可以随时访问req,res)
    中间件类型:
    1. 应用级中间件
    2. 路由级中间件
    3. 错误处理
    4. 内置
    5. 第三方
 */
const express = require('express');
const app = express();
let total = 0;

//全局的
app.use('',(req,res,next)=>{
    console.log('有人访问');
    //next方法的作用就是把请求传递到下一个中间件(函数)
    next();
});

app.use('/user',(req,res,next)=>{
    console.log(Date.Now());
    //next方法的作用就是把请求传递到下一个中间件(函数)
    next();
});

app.use('/user',(req,res,next)=>{
    console.log("访问了/user");
    next();
});

app.use('/user',(req,res)=>{
    totaL++;
    console.log(total);
    res.send("user");
});

app.listen(3000,()=>{
    console.log('服务启动……');
});

示例2(路由级)

/*
    中间件的挂载方式和执行流程
    use
    路由方式:get,post,put,delete
 */
const express = require('express');
const app = express();

// app.get('/abc',(req,res,next)=>{
//     console.log(1);
//     // next();
//     //跳转到下一个路由
//     next('route');
// },(req,res) =>{
//     console.log(2);
//     res.send('abc');
// });
//
// app.get('/abc',(req,res)=>{
//     console.log(3);
//     res.send('hello');
// });
//==============================================
// //使用回调函数数组处理路由
// var cb0 = function (req, res, next) {
//     console.log('CB0');
//     next();
// }
//
// var cb1 = function (req, res, next) {
//     console.log('CB1');
//     next();
// }
//
// var cb2 = function (req, res) {
//     res.send('Hello from C!');
// }

// app.get('/example', [cb0, cb1, cb2]);
//============================================
//混合使用
var cb0 = function (req, res, next) {
    console.log('CB0');
    next();
}

var cb1 = function (req, res, next) {
    console.log('CB1');
    next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
    console.log('the response will be sent by the next function ...');
    next();
}, function (req, res) {
    res.send('Hello from D!');
});

app.listen(3000,()=>{
    console.log('服务已启动……');
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐