Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Express中的应用程序级中间件与HTTP处理程序回调_Javascript_Node.js_Express - Fatal编程技术网

Javascript Express中的应用程序级中间件与HTTP处理程序回调

Javascript Express中的应用程序级中间件与HTTP处理程序回调,javascript,node.js,express,Javascript,Node.js,Express,说明只能对HTTP处理程序使用next('route') 您可以提供多个回调函数,其行为类似于中间件来处理请求。唯一的例外是,这些回调可能调用next('route')来绕过其余的路由回调。您可以使用此机制对路由施加先决条件,然后在没有理由继续当前路由的情况下将控制权传递给后续路由 这似乎意味着使用next('route')可以跳出数组链,跳过数组的其余部分,直接跳转到代码中调用完全相同路径的HTTP处理程序的下一个单独语句: const express = require('express')

说明只能对HTTP处理程序使用
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之间的唯一区别?还是有另一个惊喜潜伏在某处