有没有之间的差异非常有用app.all('*', ... )
,并app.use('/', ...)
在Node.js的Express吗?
hun*_*tis 116
在大多数情况下,他们会等效地工作.最大的区别是中间件的应用顺序:
app.all()
附加到应用程序的路由器,所以只要到达app.router中间件(它处理所有方法路由...... GET,POST等)就会使用它.
app.use()
附加到应用程序的主要中间件堆栈,因此它按中间件指定的顺序使用.例如,如果你把它放在第一位,它将是第一个运行.如果你把它放在最后,(在路由器之后),它通常根本不会运行.
通常,如果您想对所有路由进行全局操作,app.use()是更好的选择.此外,它具有更少的未来错误机会,因为快递0.4可能会丢弃隐式路由器(意思是,中间件中路由器的位置将比现在更重要,因为您在技术上甚至不必使用它马上).
Pal*_*ani 78
app.use只有一个回调函数,它适用于中间件.中间件通常不处理请求和响应(技术上他们可以),它们只处理输入数据,并将其移交给队列中的下一个处理程序.
app.use([path], function)
Run Code Online (Sandbox Code Playgroud)
app.all需要多次回调,并且用于路由.通过多个回调,您可以过滤请求并发送响应.它在express.js上的Filters中进行了解释
app.all(path, [callback...], callback)
Run Code Online (Sandbox Code Playgroud)
app.use只查看url是否以指定的路径开头
app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/foo
Run Code Online (Sandbox Code Playgroud)
app.all将匹配完整路径
app.all( "/product" , handler);
// will match /product
// won't match /product/cool <-- important
// won't match /product/foo <-- important
app.all( "/product/*" , handler);
// won't match /product <-- Important
// will match /product/
// will match /product/cool
// will match /product/foo
Run Code Online (Sandbox Code Playgroud)
dae*_*981 14
app.use:
惊恐:
看看这个expressJs代码示例:
var express = require('express');
var app = express();
app.use(function frontControllerMiddlewareExecuted(req, res, next){
console.log('(1) this frontControllerMiddlewareExecuted is executed');
next();
});
app.all('*', function(req, res, next){
console.log('(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next');
next();
});
app.all('/hello', function(req, res, next){
console.log('(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next');
next();
});
app.use(function frontControllerMiddlewareNotExecuted(req, res, next){
console.log('(4) this frontControllerMiddlewareNotExecuted is not executed');
next();
});
app.get('/hello', function(req, res){
console.log('(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response');
res.send('Hello World');
});
app.listen(80);
Run Code Online (Sandbox Code Playgroud)
这是访问路径'/ hello'时的日志:
(1) this frontControllerMiddlewareExecuted is executed
(2) route middleware for all method and path pattern "*", executed first and can do stuff before going next
(3) route middleware for all method and path pattern "/hello", executed second and can do stuff before going next
(5) route middleware for method GET and path patter "/hello", executed last and I do my stuff sending response
Run Code Online (Sandbox Code Playgroud)
小智 11
使用时app.use()
,"mount"路径被剥离,中间件功能不可见:
app.use('/static', express.static(__dirname + '/public'));
Run Code Online (Sandbox Code Playgroud)
express.static
除非req.url
包含此前缀(/static
),否则不会调用已安装的中间件函数(),此时调用该函数时会将其剥离.
有app.all()
,没有那种行为.
归档时间: |
|
查看次数: |
54337 次 |
最近记录: |