在 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.