All (’*’)和 app.use (’/’)之间的区别

在 Node.js 上运行的 Express.js 中,app.all("*", … )app.use("/", … )有什么有用的区别吗?

69993 次浏览

在大多数情况下,它们的工作原理是一样的,最大的区别在于中间件的应用顺序:

  • app.all()连接到应用程序的路由器上,因此每当到达 app.router中间件(它处理所有的方法路由... ... GETPOST等等)时就使用它。

注意: app.router已被废弃在快递4.x

  • app.use()附加到应用程序的主中间件堆栈上,因此按照中间件指定的顺序使用它,例如,如果您将它放在第一位,它将是第一个运行的。如果你把它放在最后(在路由器之后) ,它通常根本不会运行。

通常,如果您希望对所有路由执行全局操作,app.use()是更好的选择。另外,由于 Express 0.4可能会丢弃隐式路由器,因此未来出现 bug 的可能性更小(这意味着,路由器在中间件中的位置比现在更重要,因为从技术上讲,你现在甚至不需要使用它)。

是的,当使用任何类型的请求方法(POST、 GET、 PUT 或 DELETE)请求特定 URI 时,将调用 app.all()

另一方面,app.use()用于您可能拥有的任何中间件,它挂载到一个路径前缀上,并且将在请求该路由下的 URI 时被调用。

这是 Appall应用,使用的文档。

使用 app.use(),“ mount”路径被剥离,中间件函数不可见:

app.use('/static', express.static(__dirname + '/public'));

除非 req.url包含这个前缀(/static) ,否则不会调用挂载的中间件函数(express.static)。

对于 app.all(),不存在这种行为。

  • 应用:

    1. 注入中间件到您的前端控制器配置,例如: 头,cookie,会话等。
    2. 必须在 app [ http _ method ]之前编写,否则将不执行。
    3. 按照写入顺序处理多个调用
  • App.all:

    1. (如 app [ http _ method ])用于配置路由器的控制器
    2. “ all”意味着它适用于所有 http 方法。
    3. 按照写入顺序处理多个调用

看看这个 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);

以下是访问路由’/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

Use 只有一个回调函数,它是用于中间件的。中间件通常不处理请求和响应,(技术上它们可以)它们只处理输入数据,并将其移交给队列中的下一个处理程序。

app.use([path], function)

All 接受多个回调,用于路由。使用多个回调,您可以过滤请求并发送响应。它在 < a href = “ https://stackoverflow. com/questions/8763504/filter-on-Express-js”> Filters on Express.js 中进行了解释

app.all(path, [callback...], callback)

Use 只查看 url 是否以指定的路径开始

app.use( "/product" , mymiddleware);
// will match /product
// will match /product/cool
// will match /product/foo

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

上述答案没有提到两个差异。

第一个:
app.all接受正则表达式作为其路径参数。 app.use不接受正则表达式。

第二个:
app.all(path, handler)app[method](path, handler)处理程序的 path必须与 所有path相同。也就是说,app[method]路径已经完成。

如果 use的路径是完整的,处理程序的路径必须是 /。如果 use的路径是完整路径的开始,处理程序路径必须是完整路径的其余部分。

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 matches `/users/users` path
router.get("/users", function (req, res, next) {
res.send("respond with a resource");
});
app.all("/users", users);


//others.js: the handler will be called when matches `/`path
router.get("/", function (req, res, next) {
res.send("respond with a resource");
});
//users.js: the handler will be called when matches `/users` path
router.get("/users", function (req, res, next) {
res.send("respond with a resource");
});

主要有两个不同之处:

1. 模式匹配(答案由帕拉尼提供)
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.

链接: < a href = “ http://Expressjs.com/en/guide/using-dleware.html”rel = “ nofollow norefrer”> http://expressjs.com/en/guide/using-middleware.html

从以下例子可以看出 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();});