node.js Express中使用的参数“next”是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10695629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the parameter "next" used for in Express?
提问by Menztrual
Suppose you have a simple block of code like this:
假设你有一个像这样的简单代码块:
app.get('/', function(req, res){
res.send('Hello World');
});
This function has two parameters, reqand res, which represent the request and response objects respectively.
该函数有两个参数req和res,分别代表请求和响应对象。
On the other hand, there are other functions with a third parameter called next. For example, lets have a look at the following code:
另一方面,还有其他具有第三个参数的函数,称为next。例如,让我们看看下面的代码:
app.get('/users/:id?', function(req, res, next){ // Why do we need next?
var id = req.params.id;
if (id) {
// do something
} else {
next(); // What is this doing?
}
});
I can't understand what the point of next()is or why its being used. In that example, if id doesn't exist, what is nextactually doing?
我不明白这next()是什么意思或为什么使用它。在那个例子中,如果 id 不存在,那么next实际上在做什么?
采纳答案by Ashe
It passes control to the next matchingroute. In the example you give, for instance, you might look up the user in the database if an idwas given, and assign it to req.user.
它将控制权传递给下一个匹配的路由。例如,在您给出的示例中,如果id给定an,您可能会在数据库中查找用户,并将其分配给req.user。
Below, you could have a route like:
在下面,您可以有一条路线,例如:
app.get('/users', function(req, res) {
// check for and maybe do something with req.user
});
Since /users/123 will match the route in your example first, that will first check and find user 123; then /userscan do something with the result of that.
由于 /users/123 将首先匹配您示例中的路由,因此将首先检查并找到 user 123;然后/users可以对结果做一些事情。
Route middlewareis a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Usersmodel with an async findOne():
不过,在我看来,路由中间件是一种更灵活、更强大的工具,因为它不依赖于特定的 URI 方案或路由排序。我倾向于对这样显示的示例进行建模,假设Users模型具有 async findOne():
function loadUser(req, res, next) {
if (req.params.userId) {
Users.findOne({ id: req.params.userId }, function(err, user) {
if (err) {
next(new Error("Couldn't find user: " + err));
return;
}
req.user = user;
next();
});
} else {
next();
}
}
// ...
app.get('/user/:userId', loadUser, function(req, res) {
// do something with req.user
});
app.get('/users/:userId?', loadUser, function(req, res) {
// if req.user was set, it's because userId was specified (and we found the user).
});
// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
req.user.items.append(req.item.name);
});
Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:
能够像这样控制流量非常方便。您可能希望某些页面仅对具有管理员标志的用户可用:
/**
* Only allows the page to be accessed if the user is an admin.
* Requires use of `loadUser` middleware.
*/
function requireAdmin(req, res, next) {
if (!req.user || !req.user.admin) {
next(new Error("Permission denied."));
return;
}
next();
}
app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
res.send('blahblahblah');
});
Hope this gave you some inspiration!
希望这给了你一些启发!
回答by rajesk
I also had problem understanding next() , but thishelped
我也有问题理解的next(),但这种帮助
var app = require("express")();
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write("Hello");
next(); //remove this and see what happens
});
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write(" World !!!");
httpResponse.end();
});
app.listen(8080);
回答by Mav55
Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail.
It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World');
在理解之前next,您需要对节点中的请求-响应循环有一点了解,尽管没有太多细节。它从您对特定资源发出 HTTP 请求开始,并在您将响应发送回用户时结束,即当您遇到类似 res.send('Hello World'); 的内容时。
let's have a look at a very simple example.
让我们看一个非常简单的例子。
app.get('/hello', function (req, res, next) {
res.send('USER')
})
Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.
这里我们不需要next(),因为resp.send会结束循环,将控制权交还给路由中间件。
Now let's take a look at another example.
现在让我们看另一个例子。
app.get('/hello', function (req, res, next) {
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.
这里我们有 2 个用于同一路径的中间件函数。但你总是会得到第一个的回应。因为它首先安装在中间件堆栈中, res.send 将结束循环。
But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let's modify the above code and see what happens.
但是如果我们总是不想要“Hello World !!!!”怎么办?回复。对于某些情况,我们可能需要“Hello Planet !!!!” 回复。让我们修改上面的代码,看看会发生什么。
app.get('/hello', function (req, res, next) {
if(some condition){
next();
return;
}
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
What's the nextdoing here. And yes you might have gusses. It's gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!"response.
什么是next在这里做。是的,你可能有胆量。如果条件为真,它将跳过第一个中间件函数并调用下一个中间件函数,您将获得"Hello Planet !!!!"响应。
So, next pass the control to the next function in the middleware stack.
因此,接下来将控制权传递给中间件堆栈中的下一个函数。
What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.
如果第一个中间件函数不发回任何响应,而是执行一段逻辑,然后您从第二个中间件函数返回响应,该怎么办。
Something like below:-
类似于以下内容:-
app.get('/hello', function (req, res, next) {
// Your piece of logic
next();
});
app.get('/hello', function (req, res, next) {
res.send("Hello !!!!");
});
In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();
在这种情况下,您需要调用两个中间件函数。因此,到达第二个中间件函数的唯一方法是调用 next();
What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.
如果你不打电话给next怎么办。不要期望自动调用第二个中间件函数。调用第一个函数后,您的请求将被搁置。第二个函数永远不会被调用,你也不会得到响应。
回答by Ronique Ricketts
Next is used to pass control to the next middleware function. If not the request will be left hanging or open.
Next 用于将控制权传递给下一个中间件函数。如果不是,请求将被挂起或打开。
回答by Binayak Gouri Shankar
Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”.
调用此函数会调用应用程序中的下一个中间件函数。next() 函数不是 Node.js 或 Express API 的一部分,而是传递给中间件函数的第三个参数。next() 函数可以命名为任何名称,但按照惯例,它始终命名为“next”。
回答by AGrush
Executing the nextfunction notifies the server that you are done with this middleware step and it can execute next step in the chain.
执行该next函数会通知服务器您已完成此中间件步骤,并且它可以执行链中的下一步。

