Express中间件的使用

Express 是一个自身功能 极简,完全是由路由和中间件构成的一个web开发框架,从本质上来说,一个Express 应用就是在调用各种中间件。

中间件就是匹配路由之前或者匹配路由完成时所作的一系列的操作,叫做中间件。

  • 中间件的结构:
app.use([path, ] callback [, callback ...])

// 1. path是可选的参数,为路由的url, 如果省略将匹配到所有路径
// 2. callback中间件函数,当路由匹配成功执行函数,函数将接受三个参数(
// req: HTTP请求对象, res: HTTP响应对象, next: 处理完后交给下一个路由,若不调用则处理到此为止,不会继续后面的操作。)
  • 代码示例:
// 中间件
const express = require('express');

const app = express();

// 创建第一个中间件
app.use((req, res, next) => {
    console.log(111);
})

// 创建第二个中间件
app.use((req, res, next) => {
    console.log(222);  
})

app.listen(3000, () => console.log('Server port 3000 at start....'));

当不加上路径的时候会匹配所有路由路径,但是如果不加上尾函数next那么会无法进入到下一个中间件,也就是说网页会出现停滞状态(一直处于加载状态)。

  • 尾函数:
    如果在中间件里不调用next函数,整个请求响应的流程会中断,不会继续往下执行。
// 中间件
const express = require('express');

const app = express();

// 创建第一个中间件
app.use((req, res, next) => {
    console.log(111);
    next()
})

// 创建第二个中间件
app.use((req, res, next) => {
    console.log(222);  
})

app.listen(3000, () => console.log('Server port 3000 at start....'));

// 111 
// 222
  • 洋葱模型:
    中间件的洋葱模型在于,执行到尾函数,就去执行下一个中间件,也就是说最先进去的最后出来。

    图1.png

  • 示例代码:

// 中间件
const express = require('express');

const app = express();

// 创建第一个中间件
app.use((req, res, next) => {
    console.log('middleware_1: 111');
    next()
    console.log('middleware_1: 222');
})

// 创建第二个中间件
app.use((req, res, next) => {
    console.log('middleware_2: aaa');  
    next();
    console.log('middleware_2: bbb');
});

// 创建第三个中间件
app.use((req, res, next) => {
    console.log('middleware_3: 布局');  
    next();
    console.log('middleware_3: 测试');
});

// middleware_1: 111
// middleware_2: aaa
// middleware_3: 布局
// middleware_3: 测试
// middleware_2: bbb
// middleware_1: 222



app.listen(3000, () => console.log('Server port 3000 at start....'));
  • 对不同路由路径设置中间件:
    这一块需要注意的是,该路由匹配模式并非是完整的路径匹配,而是模糊路径匹配。
// 中间件
const express = require('express');

const app = express();

app.use('/student', (req, res, next) => {
    res.send('<h1>学生界面</h1>')
    next();
})

app.use('/', (req, res, next) => {
    res.send(`<h1>首页界面</h1>`);
})

app.listen(3000, () => console.log('Server port 3000 at start....'));
  • 多个回调函数的中间件:
    在写多个回调函数的中间件时,也需要添加next()尾函数,next() 指的是进入下一个中间件或者是进入当前中间件的下一个回调函数!
// 中间件
const express = require('express');

const app = express();

// 多个回调函数的中间件
// next() 指的是进入下一个中间件或者是进入当前中间件的下一个回调函数!
app.use((req, res, next) => {
    console.log(111);
    next();
    console.log(1110111);
}, (req, res, next) => {
    console.log(222);
    next();
    console.log(2220222);
}, (req, res, next) => {
    console.log(333);
    next();
    console.log(3330333);
})

app.use((req, res, next) => {
    console.log(444);
    next();
    console.log(4440444);
});

// 111
// 222
// 333
// 444
// 4440444
// 3330333
// 2220222
// 1110111

app.listen(3000, () => console.log('Server port 3000 at start....'));
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容