Express中使用的“ next”参数是什么?

node.js Node.js

神无番长

2020-03-19

假设您有一个简单的代码块,如下所示:

app.get('/', function(req, res){
    res.send('Hello World');
});

此函数有两个参数reqres,分别代表请求和响应对象。

另一方面,其他函数的第三个参数称为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?
    }
});

我不明白它的意义next()什么,为什么要使用它。在该示例中,如果id不存在,那么next实际上在做什么?

第2284篇《Express中使用的“ next”参数是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
GilStafan 2020.03.19

调用此函数将调用应用程序中的下一个中间件函数。next()函数不是Node.js或Express API的一部分,而是传递给中间件函数的第三个参数。next()函数可以命名为任何名称,但按照惯例,它始终命名为“ next”。

路易Sam神无 2020.03.19

Next用于将控制权传递给下一个中间件功能。否则,请求将被挂起或打开。

斯丁村村 2020.03.19

执行该next功能会通知服务器您已完成此中间件步骤,并且可以执行链中的下一步。

神乐阿飞Itachi 2020.03.19

我也有问题理解的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);

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android