Javascript Express中的应用程序级中间件与HTTP处理程序回调
说明只能对HTTP处理程序使用Javascript Express中的应用程序级中间件与HTTP处理程序回调,javascript,node.js,express,Javascript,Node.js,Express,说明只能对HTTP处理程序使用next('route') 您可以提供多个回调函数,其行为类似于中间件来处理请求。唯一的例外是,这些回调可能调用next('route')来绕过其余的路由回调。您可以使用此机制对路由施加先决条件,然后在没有理由继续当前路由的情况下将控制权传递给后续路由 这似乎意味着使用next('route')可以跳出数组链,跳过数组的其余部分,直接跳转到代码中调用完全相同路径的HTTP处理程序的下一个单独语句: const express = require('express')
next('route')
您可以提供多个回调函数,其行为类似于中间件来处理请求。唯一的例外是,这些回调可能调用next('route')来绕过其余的路由回调。您可以使用此机制对路由施加先决条件,然后在没有理由继续当前路由的情况下将控制权传递给后续路由
这似乎意味着使用next('route')
可以跳出数组链,跳过数组的其余部分,直接跳转到代码中调用完全相同路径的HTTP处理程序的下一个单独语句:
const express = require('express');
let ret = "";
const app = express();
app.all("/foo", [function(req, res, next){
let x = Math.round(Math.random()) ? 'route' : null; // 50% chance for `x` being set to "route"
ret = "foo1/";
next(x); // skip the next function if `x` equals "route"
}, function(req, res, next){
ret += "foo2/";
next();
}]);
app.all("/foo", function(req, res, next){
ret += "foo3";
res.send(ret);
});
app.listen(3000);
因此,对localhost:3000/foo
的请求应该会使服务器随机返回foo1/foo2/foo3
或foo1/foo3
,这似乎是可行的
这是应用程序无法做到的。请使用。将app.all
替换为app.use
将导致localhost:3000/foo
始终返回foo1/foo2/foo3
。即next(…)
永远不会脱离数组链,不管给定的参数是什么
但这似乎不是唯一的区别,如果我们谈论的是实际使用的话。在文件的另一部分中,它说:
路由将立即用“/”匹配其路径后面的任何路径。例如:app.use('/apple',…)将匹配“/apple”、“/apple/images”、“/apple/images/news”等
由于路径默认为“/”,因此将对应用程序的每个请求执行未安装路径的中间件
我们可以通过以下方式利用这一点:
const express = require('express');
let ret = ""; // a string we want build and return to the client
const app = express();
app.use(function(req, res, next){ // implicitly bound to "/"
ret = "/"; // reset `ret` to "/"
next();
});
app.use("/foo", function(req, res, next){
ret += "foo/";
next();
});
app.use("/foo/bar", function(req, res, next){
ret += "bar";
res.send(ret);
});
app.use(function(req, res, next){
res.send(ret); // finally return the string
});
app.listen(3000);
给你:
localhost:3000/
=>/
localhost:3000/foo/
=>/foo/
localhost:3000/foo/bar
=>/foo/bar
它可以在多次请求后工作
localhost:3000/foo/asdf
触发app.use(“/”,…)
(带有“/”
隐式)和app.use(“/foo”,…),服务器也返回/foo`
将app.替换为app.使用app.以上代码中的所有都会将其破坏
现在,这些是否真的是应用程序级中间件和app.use
与HTTP处理程序回调和app.all之间的唯一区别?还是有另一个惊喜潜伏在某处