next not working properly in middleware using Nodejs
P粉076987386
P粉076987386 2024-04-04 17:33:56
0
1
395

I'm working with Nodejs and using expressjs and now I'm looking into middleware functionality and I'm wondering what's the "next" job in middleware concepts? "Next into next middleware", but what is "next middleware"? I tried using the following code and whenever I hit "http://localhost:3000/" then it shows "Middleware 1 and Middleware 2" in console and browser "hello world" is always displayed, so "next middleware" always means "router handler" (get method)?

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

reply all(1)
P粉327903045

This is wrong. Next middleware doesn't always mean "router handler". Next() function redirects to another function.

For example, the following example,

// 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!");
});

Console output:

The response in the browser is Hello, world!. Therefore, the next() function is not always meant as a router handler.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!