node.js app.all('*') 和 app.use('/') 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14125997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between app.all('*') and app.use('/')
提问by ostergaard
Is there a useful difference between app.all('*', ... )and app.use('/', ...)in Node.JS Express?
Node.JS Expressapp.all('*', ... )和app.use('/', ...)Node.JS Express之间有什么有用的区别吗?
回答by hunterloftis
In most cases they would work equivalently. The biggest difference is the order in which middleware would be applied:
在大多数情况下,它们会等效地工作。最大的区别是中间件的应用顺序:
app.all()attaches to the application's router, so it's used whenever the app.router middleware is reached (which handles all the method routes... GET, POST, etc).
app.all()附加到应用程序的路由器,因此只要到达 app.router 中间件(它处理所有方法路由……GET、POST 等)就会使用它。
NOTICE: app.router has been deprecated in express 4.x
注意:app.router 已在 express 4.x 中弃用
app.use()attaches to the application's main middleware stack, so it's used in the order specified by middleware. eg, if you put it first, it will be the first thing to run. If you put it last, (after the router), it usually won't be run at all.
app.use()附加到应用程序的主中间件堆栈,因此按中间件指定的顺序使用它。例如,如果你把它放在第一位,它将是第一个运行的东西。如果你把它放在最后(在路由器之后),它通常根本不会运行。
Usually, if you want to do something globally to all routes, app.use() is the better option. Also, it has less chance of future bugs, since express 0.4 will probably drop the implicit router (meaning, the position of the router in middleware will be more important than it is right now, since you technically don't even have to use it right now).
通常,如果您想对所有路由执行全局操作, app.use() 是更好的选择。此外,它未来出现错误的可能性较小,因为 express 0.4 可能会丢弃隐式路由器(这意味着,路由器在中间件中的位置将比现在更重要,因为从技术上讲,您甚至不必使用它马上)。
回答by Palani
app.usetakes only one callback function and it's meant for Middleware. Middleware usually doesn't handle request and response, (technically they can) they just process input data, and hand over it to next handler in queue.
app.use只需要一个回调函数,它适用于中间件。中间件通常不处理请求和响应,(从技术上讲他们可以)它们只是处理输入数据,并将其交给队列中的下一个处理程序。
app.use([path], function)
app.alltakes multiple callbacks, and meant for routing. with multiple callbacks you can filter requests and send responses. Its explained in Filters on express.js
app.all接受多个回调,用于路由。通过多个回调,您可以过滤请求并发送响应。它在 express.js 上的过滤器中进行了解释
app.all(path, [callback...], callback)
app.useonly sees whether url starts with the specified path
app.use只看 url 是否以指定路径开头
app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/foo
app.allwill match complete path
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
回答by daemon1981
app.use:
- inject middlware to your front controller configuring for instance: header, cookies, sessions, etc.
- must be written before app[http_method] otherwise there will be not executed.
- several calls are processed in the order of writing
app.all:
- (like app[http_method]) is used for configuring routes' controllers
- "all" means it applies on all http methods.
- several calls are processed in the order of writing
应用程序使用:
- 将中间件注入您的前端控制器配置,例如:标头、cookie、会话等。
- 必须写在app[http_method]之前,否则不会执行。
- 几个调用按写入顺序处理
惊恐:
- (如 app[http_method])用于配置路由的控制器
- “all”表示它适用于所有 http 方法。
- 几个调用按写入顺序处理
Look at this expressJs code sample:
看看这个 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);
Here is the log when accessing route '/hello':
这是访问路由'/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
回答by better9
With app.use(), the "mount" path is stripped and is not visible to the middleware function:
使用app.use(),“挂载”路径被剥离并且对中间件功能不可见:
app.use('/static', express.static(__dirname + '/public'));
Mounted middleware functions(express.static) are not invoked unless the req.urlcontains this prefix (/static), at which point it is strippedwhen the function is invoked.
express.static除非req.url包含此前缀 ( /static),否则不会调用挂载的中间件函数 ( ) ,此时在调用函数时将其剥离。
With app.all(), there is no that behavior.
使用app.all(),则没有这种行为。
回答by Gurpreet Singh
Yes, app.all()gets called when a particular URI is requested with any type of request method (POST, GET, PUT, or DELETE)
是的,app.all()当使用任何类型的请求方法(POST、GET、PUT 或 DELETE)请求特定 URI 时调用
On other hand app.use()is used for any middleware you might have and it mounts onto a path prefix, and will be called anytime a URI under that route is requested.
另一方面app.use(),用于您可能拥有的任何中间件,它安装在路径前缀上,并且将在请求该路由下的 URI 时随时调用。
回答by Hymanzhoumine
Two differences all above answers don't metion.
以上两个不同的答案都没有提到。
The fisrt one: app.allaccepts a regex as its path parameter. app.usedoes NOT accept a regex.
第一个:app.all接受一个正则表达式作为它的路径参数。app.use不接受正则表达式。
The second one:
app.all(path,handler)or app[method](path,handler),handler's pathmust be same to all'spath. This is,app[method]'path is complete.
第二个:
app.all(path,handler)or app[method](path,handler),handler'spath必须与all's相同path。这是,app[method]'路径完成。
app.use(path,hanlder),if use's path is complete,the hanlder's path must be '/'.if the use's path is the start of the complete path,the handler path must be the rest of the complete path.
app.use(path,hanlder),如果use的路径是完整的,则handler的路径必须是'/'。如果use的路径是完整路径的开始,则handler的路径必须是完整路径的其余部分。
app.use('/users', users);
//users.js: the handler will be called when matchs `/user/` path
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
// others.js: the handler will be called when matchs `/users/users` path
router.get('/users', function(req, res, next) {
res.send('respond with a resource');
});
app.all('/users', users);
//others.js: the handler wil be called when matchs `/`path
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
//users.js: the handler will be called when matchs `/users` path
router.get('/users', function(req, res, next) {
res.send('respond with a resource');
});
回答by Ng Ju Ping
There are two main differences:
1. pattern matching (answer given by Palani)
2. next(route)won't work inside the function body of middleware loaded using app.use. This is stated in the link from the docs:
有两个主要区别:
1. 模式匹配(Palani 给出的答案)
2.next(route)在使用app.use. 这在文档的链接中说明:
NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.
Link: http://expressjs.com/en/guide/using-middleware.html
链接:http: //expressjs.com/en/guide/using-middleware.html
The working effect of next('route')can be seen from the following example:
的工作效果next('route')可以从下面的例子中看出:
app.get('/',
(req,res,next)=>{console.log("1");
next(route); //The code here skips ALL the following middlewares
}
(req,res,next)=>{next();}, //skipped
(req,res,next)=>{next();} //skipped
);
//Not skipped
app.get('/',function(req,res,next){console.log("2");next();});

