我正在测试 middleware 在里面 express 我遇到了一个问题。
middleware
express
在我的第二行中,我使用 app.use 调用testOne和testTwo。当我在浏览器中访问我的根目录/时,这两个 中间件 函数运行。然而,如果我访问一个随机的静态文件,例如图像。png或大约。他们不会开火。无论我请求什么文件,我都要如何让他们开火?非常感谢您的帮助!
app.use
中间件
app.use(express.static(path.join(__dirname, 'public'))); app.use(testOne, testTwo); function testOne(request, response, next) { console.log('testOne ran'); } function testTwo(request, response, next) { console.log('testTwo ran'); } app.get('/', function(request, response) { response.sendFile(path.join(__dirname, 'public/index.htm')); });
所有中间件都必须调用 next() 以便继续路由到下一个路由处理程序。
next()
app.use(testOne, testTwo); function testOne(request, response, next) { console.log('testOne ran'); next(); } function testTwo(request, response, next) { console.log('testTwo ran'); next(); } app.use(express.static(path.join(__dirname, 'public')));
如果你不打电话 下一个() 这条路线只是停滞不前,什么都不做(直到它可能最终超时为止)。
下一个()
此外,如果希望这些中间件触发所有请求,那么需要将它们放在其他可能实际处理请求的请求处理程序之前,例如 express.static() .
express.static()