next 在使用 Nodejs 的中间件中无法正常工作
P粉076987386
P粉076987386 2024-04-04 17:33:56
0
1
347

我正在使用 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学习者快速成长!