Entdecken Sie die Funktionalität der „nächsten' Funktion in der Express-Middleware und ihre Rolle bei der Umleitung zu einer anderen Funktion.
P粉195402292
P粉195402292 2024-04-02 21:02:16
0
1
476

Ich bin neu bei Nodejs und arbeite an Express js. Jetzt arbeite ich an „Middleware-Funktionen“ für eine bestimmte Route und möchte wissen, „wofür als nächstes verwendet wird“, d. h. nachdem ich überprüft habe, was die „nächste“ Funktion tun kann? Wenn wir zu einer anderen Funktion wechseln/umleiten möchten, wie machen wir das? Was ist „checkAuthentication“? Das ist mein aktueller Code

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粉195402292
P粉195402292

Antworte allen(1)
P粉738676186

接下来是传递给中间件函数的回调函数。您可以在不同的框架中找到它的不同名称,但概念保持不变。

我将尝试通过您的代码本身来解释中间件。

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.
}
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage