Home  >  Q&A  >  body text

next not working properly in middleware using Nodejs

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粉076987386P粉076987386178 days ago357

reply all(1)I'll reply

  • P粉327903045

    P粉3279030452024-04-05 16:56:37

    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.

    reply
    0
  • Cancelreply