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


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

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

语法

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

参数

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

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

示例 1

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

无 next() 函数

// next() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating a Middleware
app.use("/", (req, res, next) => {
   console.log("Welcome to TutorialsPoint");
   // There is no next() function calls here
})

// Creating another middlware
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
ode>> node next.js Server listening on PORT 3000 Welcome to TutorialsPoint

示例 2

让我们再看一个例子

// next() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating a Middleware
app.use("/", (req, res, next) => {
   console.log("Welcome to TutorialsPoint");

   // Calling the next() function here
   next();
})

// Creating another middlware
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 端点调用 **first** 函数和 **next** 函数。

输出

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

更新于:2021年10月1日

浏览量 1K+

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.