Express使用注意事项

Express使用注意事项:

1、中间件

1.1 app.use(sm);

如果在中间件中不显示的调用next,后续绑定到该路径的中间件将不会被调用。

1.2 中间件绑定路径为请求的跟路径匹配,即只有请求路径的跟与中间件一致就会被拦截。

如果没有绑定路径或使用'/',则所有的请求都会被该中间件拦截处理。

2、router.VERB(path,callbacks);

这里面的callbacks签名和中间件一致

callback里next机制:

如果直接调用next,会调用当前callback栈里的下一个方法,next('route'),则调用下一个route栈

实例:

router.get('/sayHello',function(req,res,next){

    console.log('say hello by router 1-1 ');

    next();

},function(req,res,next){

    console.log('say hello by router 1-2 ');

});

router.get('/sayHello',function(req,res){

    console.log('say hello by router 2-1');

});

console:

say hello by router 1-1 

say hello by router 1-2 

router.get('/sayHello',function(req,res,next){

    console.log('say hello by router 1-1 ');

    next('route');

},function(req,res,next){

    console.log('say hello by router 1-2 ');

});

router.get('/sayHello',function(req,res){

    console.log('say hello by router 2-1');

});

console:

say hello by router 1-1 

say hello by router 2-1

猜你喜欢

转载自tarsean.iteye.com/blog/2260585