简体   繁体   中英

Usage of app.use() in express/connect

I saw sample code on express website:

var express = require('express');
var app = express();

// simple logger
app.use(function(req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
});

// respond
app.use(function(req, res, next){
  res.send('Hello World');
});

app.listen(3000);

Here app.use() called functions of exactly the same signature and yet is able to run them in sequence. How is this done in javascript?

Here's definition for app.use(): https://github.com/senchalabs/connect/blob/master/lib/proto.js

Connect keeps a "stack" (an Array) of middleware and route handlers. And when a request is processed, it simply iterates through all handler functions in the stack in order and (subject to some route matching rules), invokes the handler functions.

this.stack.push({ route: route, handle: fn });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM