next 在使用 Nodejs 的中間件中無法正常運作
P粉076987386
P粉076987386 2024-04-04 17:33:56
0
1
346

我正在使用 Nodejs 並使用expressjs,現在我正在研究中間件功能,我想知道中間件概念中的「下一個」工作是什麼? “下一個進入下一個中間件”,但是什麼是“下一個中間件”?我嘗試使用以下程式碼,每當我點擊“http://localhost:3000/”,然後在控制台和瀏覽器中顯示“中間件 1 和中間件 2” 總是顯示“hello world”,所以“下一個中間件”總是意味著“路由器處理程序”(get 方法)?

const express = require('express');
const app = express();

// Middleware function 1
app.use((req, res, next) => {
  console.log('Middleware 1');
  next(); // Move to the next middleware
});

// Middleware function 2
app.use((req, res, next) => {
  console.log('Middleware 2');
  next(); // Move to the next middleware
});


// Route handler
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

P粉076987386
P粉076987386

全部回覆(1)
P粉327903045

這是錯的。下一個中間件並不總是意味著“路由器處理程序”。 Next() 函數重定向到另一個函數。

例如下面的例子,

// Middleware function 1
app.use((req, res, next) => {
  console.log("Middleware 1");
  next(); // Move to the next middleware
});

// Route handler
app.get("/", (req, res, next) => {
  console.log("GET /");
  next();
});

// Middleware function 2
app.use((req, res) => {
  console.log("Middleware 2");
  res.send("Hello, world!");
});

控制台輸出:

瀏覽器中的回應為 Hello, world!。因此,next() 函數並不總是意味著路由器處理程序。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!