app.all('*') 和 app.use('/') 的区别 [英] Difference between app.all('*') and app.use('/')
问题描述
app.all("*", ... )
和 app.use("/", ... )
在 Express 中是否有有用的区别.js 在 Node.js 上运行?
Is there a useful difference between app.all("*", … )
and app.use("/", … )
in Express.js running on Node.js?
推荐答案
在大多数情况下,它们的工作方式相同.最大的区别是中间件的应用顺序:
In most cases they would work equivalently. The biggest difference is the order in which middleware would be applied:
app.all()
附加到应用程序的路由器,因此只要到达app.router
中间件(处理所有方法路由...GET
、POST
等).
app.all()
attaches to the application's router, so it's used whenever theapp.router
middleware is reached (which handles all the method routes...GET
,POST
, etc).
注意:app.router
在 express 4.x 中已被弃用
NOTICE:
app.router
has been deprecated in express 4.x
app.use()
附加到应用程序的主中间件堆栈,所以它按照中间件指定的顺序使用,例如,如果你把它放在最前面,它将首先运行.如果你把它放在最后,(在路由器之后),它通常根本不会运行.app.use()
attaches to the application's main middleware stack, so it's used in the order specified by middleware, e.g., 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()
是更好的选择.此外,它未来出现错误的可能性较小,因为 express 0.4 可能会删除隐式路由器(这意味着路由器在中间件中的位置将比现在更重要,因为从技术上讲,您甚至不必使用它现在).
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.all('*') 和 app.use('/') 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!