【发布时间】:2016-06-11 02:48:49
【问题描述】:
我正在尝试了解中间件和路由处理程序在 Express 中的工作方式。在Web Development with Node and Express,作者给出了一个有趣的路由和中间件的例子,但没有给出实际的细节。
请有人帮助我理解以下示例中每个步骤发生的情况,以便我确定自己的想法正确吗?这是示例(以我的理解和cmets中的问题):
//get the express module as app
var app = require('express')();
//1. when this module is called, this is printed to the console, always.
app.use(function(req, res, next){
console.log('\n\nALLWAYS');
next();
});
//2. when a route /a is called, a response 'a' is sent and the app stops. There is no action from here on
app.get('/a', function(req, res){ console.log('/a: route terminated'); res.send('a');
});
//3. this never gets called as a consequence from above
app.get('/a', function(req, res){
console.log('/a: never called');
});
//4. this will be executed when GET on route /b is called
//it prints the message to the console and moves on to the next function
//question: does this execute even though route /a (2) terminates abruptly?
app.get('/b', function(req, res, next){
console.log('/b: route not terminated');
next();
});
//5. question: this gets called after above (4)?
app.use(function(req, res, next){
console.log('SOMETIMES');
next();
});
//6. question: when does this get executed? There is already a function to handle when GET on /b is called (4)
app.get('/b', function(req, res, next){
console.log('/b (part 2): error thrown' );
throw new Error('b failed');
});
//7. question: I am not sure when this gets called... ?
app.use('/b', function(err, req, res, next){
console.log('/b error detected and passed on');
next(err);
});
//8. this is executed when a GET request is made on route /c. It logs to the console; throws an error.
app.get('/c', function(err, req){
console.log('/c: error thrown');
throw new Error('c failed');
});
//9. question: this catches the above error and just moves along?
app.use('/c', function(err, req, res, next) {
console.log('/c: error deteccted but not passed on');
next();
});
//10. question: this follows the above and prints an error based on above?
//This also sends a 500 reponse?
app.use(function(err, req, res, next){
console.log('unhandled error detected: ' + err.message);
res.send('500 - server error');
});
//11. question: this is the catch all for something that falls through and sends a 404?
app.use(function(req, res){
console.log('route not handled');
res.send('404 - not found');
});
//12. This app listens on the 3000 port.
app.listen(3000, function(){
console.log('listening on 3000');
});
【问题讨论】:
-
您需要比这更具体。 究竟你不明白什么?
-
在代码中添加了我的理解和问题。
-
这就像试图一口气吃掉整个披萨。首先切成片(
app.get是做什么的?app.use是做什么的?next是什么?等等),然后对每一片进行小口切片(这意味着什么 2 个app.get调用使用相同的路径?) -
您有时间阅读我的回答吗?
标签: javascript node.js express web middleware