MST
星途 面试题库

面试题:Node.js Express中间件的执行顺序原理

在Express应用中,定义了多个中间件,如下代码: ```javascript const express = require('express'); const app = express(); app.use((req, res, next) => { console.log('Middleware 1'); next(); }); app.use((req, res, next) => { console.log('Middleware 2'); next(); }); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` 请解释这些中间件的执行顺序,并说明为什么会是这样的顺序。如果在Middleware 1中调用`next('route')`,执行顺序又会如何变化?
33.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
  1. 正常情况下中间件执行顺序
    • 当客户端向Express应用发送请求时,首先会执行app.use((req, res, next) => {...})定义的中间件。按照定义顺序,先执行Middleware 1,因为app.use定义的中间件是按照其在代码中出现的顺序依次执行的。Middleware 1执行完毕后调用next(),控制权传递给下一个中间件Middleware 2Middleware 2执行完毕后调用next(),由于没有其他app.use中间件,且请求路径匹配app.get('/', (req, res) => {...}),所以执行该路由处理函数,向客户端发送Hello World!
    • 总结来说,正常顺序为:Middleware 1 -> Middleware 2 -> 路由处理函数(app.get('/')。这是因为Express的中间件机制是基于栈的,先进后出,app.use中间件按照定义顺序依次压入栈中,请求进来时依次执行。
  2. 在Middleware 1中调用next('route')时执行顺序变化
    • 当在Middleware 1中调用next('route')时,它会跳过当前栈中剩余的app.use中间件(即Middleware 2),直接将控制权传递给路由处理函数(app.get('/')。
    • 所以执行顺序变为:Middleware 1 -> 路由处理函数(app.get('/')。next('route')的作用就是告诉Express跳过剩余的app.use中间件,直接寻找匹配的路由处理函数。