Explorez la fonctionnalité de la fonction « suivant » dans le middleware Express et son rôle dans la redirection vers une autre fonction.
P粉195402292
P粉195402292 2024-04-02 21:02:16
0
1
329

Je suis nouveau sur Nodejs et je travaille sur Express js et maintenant je travaille sur des "fonctions middleware" pour un itinéraire spécifique et je veux savoir "à quoi sert la prochaine utilisation", c'est-à-dire après avoir vérifié ce que la fonction "suivante" peut faire ? Si nous voulons nous déplacer/rediriger vers une autre fonction, comment pouvons-nous procéder ? Qu'est-ce que « checkAuthentification » ? C'est mon code actuel

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

répondre à tous(1)
P粉738676186

Vient ensuite la fonction de rappel transmise à la fonction middleware. Vous pouvez le trouver sous différents noms dans différents frameworks mais le concept reste le même.

Je vais essayer d'expliquer le middleware à travers votre code lui-même.

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.
}
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!