在 Express.js 中使用 next() 函数

Express.js 是一个强大的工具,用于构建 Web 服务器以在后端访问 API。它有几个使其流行的优点,但它也有一些缺点,例如,需要定义不同的路由或中间件来处理来自客户端的不同传入请求。

在本文中,我们将看到如何next()在 Express.js 的中间件中使用该功能。Express.js 中有很多中间件。我们将使用中间件来定义客户端发出的特定请求的处理程序。app.use()

语法

app.use(path, (req, res, next) )

参数

  • path - 这是将调用中间件的路径。

  • callback - 这是在发生任何错误或调用下一个中间件函数时将调用的回调函数。

示例 1

创建一个名为“next.js”的文件并复制以下代码片段。创建文件后,使用命令“node next.js”运行此代码。

无next()功能

// next() 演示示例

// 导入 express 模块
var express = require('express');

// 初始化 express 和端口号
var app = express();
var PORT = 3000;

// 创建中间件
app.use("/", (req, res, next) => {
   console.log("Welcome to nhooo");
   // 这里没有 next() 函数调用
})

// 创建另一个中间件
app.get("/", (req, res, next) => {
   console.log("Get Request")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

如果没有该next()函数,您可以看到只调用了第一个函数,而没有调用另一个函数。

输出结果

C:\home\node>> node next.js
Server listening on PORT 3000
Welcome to nhooo

示例 2

让我们再看一个例子

// next() 演示示例

// 导入 express 模块
var express = require('express');

// 初始化 express 和端口号
var app = express();
var PORT = 3000;

// 创建中间件
app.use("/", (req, res, next) => {
   console.log("Welcome to nhooo");

   // 在这里调用 next() 函数
   next();
})

// 创建另一个中间件
app.get("/", (req, res, next) => {
   console.log("Got Request")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

next()函数被调用时,这两个第一功能和未来功能的调用传递的API端点。

输出结果

C:\home\node>> node next.js
Server listening on PORT 3000
Welcome to nhooo
Get Request