首頁  >  問答  >  主體

探索 Express 中間件中「下一個」函數的功能及其在重定向到另一個函數中的作用。

我是Nodejs新手,正在研究Express js,現在我正在研究特定路由的“中間件函數”,我想知道“next有什麼用”,意味著在驗證“next”函數可以做什麼之後做 ?如果我們想移動/重定向到另一個函數那麼我們該怎麼做?什麼是“checkAuthentication”?這是我目前的程式碼

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

// Custom middleware function
const authMiddleware = (req, res, next) => {
  // Check if user is authenticated
  const isAuthenticated = checkAuthentication(req);
  
  if (isAuthenticated) {
    next();
  } else {
    // User is not authenticated, send an unauthorized response
    res.status(401).send('Unauthorized');
  }
};

// Middleware function is applied to specific routes
app.get('/protected', authMiddleware, (req, res) => {
  res.send('Protected Route');
});

// Route handler
app.get('/', (req, res) => {
  res.send('Home Page');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

P粉195402292P粉195402292181 天前342

全部回覆(1)我來回復

  • P粉738676186

    P粉7386761862024-04-03 16:05:48

    接下來是傳遞給中間件函數的回呼函數。您可以在不同的框架中找到它的不同名稱,但概念保持不變。

    我將嘗試透過您的程式碼本身來解釋中間件。

    const express = require('express');
    const app = express();
    
    function checkAuthentication(req) {
      /*
      I am considering this as my authentication function. 
      When the user logged in, server has sent him a token, which now will act as a validator. 
      */
    
      if (req.headers.token) {
        const user = someFunctionToFetchUser(req.header.token)
        return user
      } else {
        return false
      }
    }
    
    /*
    Now I want a function to be there on each protected api routes
    to make user if user has a valid token then only allow them to interact with the data base otherwise throw an error 
    */
    
    
    const authMiddleware = (req, res, next) => {
      // Check if user is authenticated
      const isAuthenticated = checkAuthentication(req);
    
      if (isAuthenticated) {
        // Now you have verified the has valid a token. So allow user 
        // to reach to the controller or any other middleware, if any.
        next();
      } else {
        // User is not authenticated, send an unauthorized response
        res.status(401).send('Unauthorized');
      }
    };
    
    // Middleware function is applied to specific routes
    app.get('/protected', authMiddleware, (req, res) => {
      res.send('Protected Route');
    });
    
    // You can have any number of middlewares
    app.get('/protected', authMiddleware, someOtherMiddleware, (req, res) => {
      res.send('Protected Route');
    });
    
    // And also you can pass data from middleware to next middleware/controller also by attahching it with request
    
    function newMiddleware(req, res, next) {
      req.foo = "bar" //Now you can access this foo variable in next function.
    }

    回覆
    0
  • 取消回覆