[英]Express middleware: app.use and app.all
Is there a difference between 两者之间有区别吗?
app.use('/some/path', function(req, res, next() {})
and 和
app.all('/some/path', function(req, res, next() {})
They are both middleware functions that get called for /some/path requests only, right? 它们都是中间件函数,只能被调用/某些/路径请求,对吧?
There is big difference between the use of these two examples. 使用这两个例子有很大的不同。 Functions registered with app.use
are general middleware functions and is called appropriate to their position on the middleware stack, typically inside an app.configure
function. 在app.use
中注册的app.use
是一般的中间件函数,被称为适合它们在中间件堆栈上的位置,通常在app.configure
函数内部。 This type of middleware is usually placed before app.route
, with the exception of error handling functions. 这种类型的中间件通常放在app.route
之前 ,但错误处理函数除外。
On the other hand app.all
is a routing function (not usually called middleware) which covers all HTTP methods and is called only inside app.route
. 另一方面, app.all
是一个路由功能(通常不称为中间件),它涵盖所有HTTP方法,仅在 app.route
内部 app.route
。 If any of your previous router function matches the /some/path
and did not call the next
callback, app.all
will not be executed, so app.all
functions are usually on the beginning of your routing block. 如果你以前的路由器功能的匹配/some/path
,并没有叫next
回调, app.all
不会被执行,因此app.all
功能通常是您的路由组的开始。
There is also third type of middleware, used in your routing functions, eg. 还有第三种类型的中间件,用于您的路由功能,例如。
app.get('/some/path', middleware1, middleware2, function(req, res, next) {});
which is typicaly used for limiting access or perform general tasks related to /some/path
route. 这通常用于限制访问或执行与/some/path
路由相关的一般任务。
For practical application you can use both functions, but be careful of the difference in behaviour when using app.use
with /some/path
. 对于实际应用,您可以使用这两种功能,但在将app.use
与/some/path
一起使用时要小心行为上的差异。 Unlike app.get
, app.use
strips /some/path
from the route before invoking the anonymous function. 与app.get
不同, app.use
在调用匿名函数之前从/some/path
app.use
/some/path
。
You can find more in the documentation of express . 您可以在express的文档中找到更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.