如何为每个用户设置唯一的 URL

How to have a unique url for every user

本文关键字:设置 唯一 URL 用户      更新时间:2023-09-26

路由的新代码.js和login.ejs:

`module.exports = function(app, passport) {
    // =====================================
    // HOME PAGE (with login links) ========
    // =====================================
    app.get('/', function(req, res) {
        res.render('./pages/index.ejs'); // load the index.ejs file
    });
    // =====================================
    // LOGIN ===============================
    // =====================================
    app.get('/login', function(req, res) {
        // render the page and pass in any flash data if it exists
        res.render('./pages/login.ejs', { message: req.flash('error') });
    });
    // process the login form
    app.post('/login', passport.authenticate('local-login', {
        successRedirect : '/profile', // redirect to the secure profile section
        failureRedirect : '/login', // redirect back to the signup page if there is an error
        failureFlash : true
    }));
    // =====================================
    // SIGNUP ==============================
    // =====================================
    app.get('/signup', function(req, res) {
        // render the page and pass in any flash data if it exists
        res.render('./pages/signup.ejs', { message: req.flash('signupMessage') });
    });
    // process the signup form
    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/profile', // redirect to the secure profile section
        failureRedirect : '/signup', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));
    // =====================================
    // PROFILE SECTION =========================
    // =====================================
    // we will want this protected so you have to be logged in to visit
    // we will use route middleware to verify this (the isLoggedIn function)
    app.get('/profile/:id', isLoggedIn, function (req, res) {
        var id = req.params.id;
        res.send('./pages/profile.ejs' + req.params.id);
    });
    // =====================================
    // LOGOUT ==============================
    // =====================================
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
    // =====================================
    // UPLOAD ==============================
    // =====================================
    app.get('/upload', function (req, res){
        res.render('./pages/upload.ejs');
    });
    // =====================================
    // PASSWORD RESET ======================
    // =====================================
    app.get('/forgot', isLoggedIn, function (req, res){
        res.render('./pages/forgot.ejs');
    });
    app.post('/forgot', function(req, res, next) {
  async.waterfall([
    function(done) {
      crypto.randomBytes(20, function(err, buf) {
        var token = buf.toString('hex');
        done(err, token);
      });
    },
    function(token, done) {
      User.findOne({ email: req.body.email }, function(err, user) {
        if (!user) {
          req.flash('error', 'No account with that email address exists.');
          return res.redirect('/forgot');
        }
        user.resetPasswordToken = token;
        user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
        user.save(function(err) {
          done(err, token, user);
        });
      });
    },
    function(token, user, done) {
      var smtpTransport = nodemailer.createTransport('SMTP', {
        service: 'SendGrid',
        auth: {
          user: '!!! YOUR SENDGRID USERNAME !!!',
          pass: '!!! YOUR SENDGRID PASSWORD !!!'
        }
      });
      var mailOptions = {
        to: user.email,
        from: 'passwordreset@demo.com',
        subject: 'Node.js Password Reset',
        text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.'n'n' +
          'Please click on the following link, or paste this into your browser to complete the process:'n'n' +
          'http://' + req.headers.host + '/reset/' + token + ''n'n' +
          'If you did not request this, please ignore this email and your password will remain unchanged.'n'
      };
      smtpTransport.sendMail(mailOptions, function(err) {
        req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
        done(err, 'done');
      });
    }
  ], function(err) {
    if (err) return next(err);
    res.redirect('/forgot');
  });
});

};
// route middleware to make sure
function isLoggedIn(req, res, next) {
    // if user is authenticated in the session, carry on
    if(req.isAuthenticated()){
        return next();
    }

    // if they aren't redirect them to the home page
    else{
    res.redirect('/');
    }
}`

和视图(login.ejs):

`<!DOCTYPE html>
<html>
<head>
     <% include ../partials/head %>
</head>
<body>
<div class="container">

<div class="col-sm-6 col-sm-offset-3">
    <h1><span class="fa fa-sign-in"></span>Login</h1>
        <% if(message.length > 0){ %>
        <div class="alert alert-danger"><%= message %></div>
    <% } %>
    <!-- LOGIN FORM -->
    <form action="/login" method="post">
        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" name="email">
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" name="password">
        </div>
        <button type="submit" class="btn btn-warning btn-lg">Login</button>
    </form>
    <hr>
    <p>Need an account? <a href="/signup">Signup</a></p>
    <p>Forgot your or password? <a href="/forgot">Forgot</a></p>
</div>
</div>
</body>
</html>`

我也可以像 = http://localhost:8080/profile/emailAddress .

电子邮件地址是在注册我的网站时给出的。电子邮件地址存储在我设置的数据库中。

app.get('/profile', isLoggedIn, function (req, res) {
// store userId on login into session or any global variable 
var userId = req.session.userId
   res.redirect('/profile/'+userId) 
}); // =>directs to http://localhost:8080/profile for every signup.

使用附加参数创建新路由

app.get('/profile/:id', function (req, res) {
 var id = req.params.id
 res.render('./pages/profile.ejs', {user: id});  
})

您应该使用请求参数。使用快速,您可以执行以下操作:

app.get('/profile/:id', isLoggedIn, function (req, res) {
    var id = req.params.id;
    //do with id whatever you want
    res.render('./pages/profile.ejs', {user: req.user}); 
});

在你的isLoggedIn中间件中,你会有这样的东西:

function(req, res, next) {
    if (isLoggedIn) { //check if the user is logged in
        req.user = user; //fetch the user from the DB or wherever you have it
    }
}

在您的视图中,您将使用用户的 id 来构建 url:

<a href="/profile/<%=user.id%>"><%=user.name%></a>