Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I create a sample Express application using the express binary, the bootstrap code has these lines:

...

var app = express();
...
app.use(app.router);

I didn't find much about app.router. I thought that this is the middleware that handles the routing (app.get(), app.post() etc.) rules, but these rules also get executed when I remove the app.use(app.router); line.

So what is the exact purpuse of this middleware?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
371 views
Welcome To Ask or Share your Answers For Others

1 Answer

In Express 3.x, app.router is an enhanced version of the connect middleware router. As hector said, this is where Express handles the request handlers registered with app.get, app.post, etc.

If you do not call app.use(app.router) explicitly then express will call it implicitly the first time you use app.get(...), app.post(...), etc. However, you may want to .use it explicitly, because then you choose the order of all your middleware.

app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
// app.get, app.post, etc called before static folder
app.use(app.router); 
app.use(express.static(path.join(__dirname, 'public')));

See how the router is retrieved in the Express 3 source here.

Note that Express 4 doesn't need app.router.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...