简体   繁体   中英

How to pass a link to req.flash() in express.js

I have been trying to figure out a way of passing a link in req.flash() in my js file, without actually doing that in html template, because am using the alert message as a partial in other html pages, I wish to pass in resend verification link, is there a way around this, or do i really have to create another req.flash for verify

app.use(function(req,res,next){
    res.locals.error = req.flash("error");
    res.locals.success = req.flash("success")
    next();
})

router.get("/verification", function(req,res){
    verification coding stuff here
})

the verification route is the link that i wish to pass in the req.flash('error')

router.get('/verify/:token', function(req,res){
  User.findOne({ verificationToken: req.params.token, resetPasswordExpires: { $gt: Date.now()}}, function(err, user){
      if(err){
          console.log(err);
          //here is where i wish to pass in the link for verification link//
          req.flash('error', 'Mail verify token is invalid or has expired' + resend link here + '.')
          return res.redirect('/forgot')
      } else {
          user.active = "true"
          user.save()
          console.log(user.active);
          req.flash('success', 'Your mail have been verified successfully')
          res.redirect('/login');
      }
  })
})

<% if(error && error.length > 0) { %>
    <div class="alert alert-danger alert-dismissible deposit-alert" role="alert">
        <div class="container">
            <%= error %>
        </div>
    </div>
<% } %>

The following should work for you.

Controller::

router.get('/verify/:token', function(req,res){
  User.findOne({ verificationToken: req.params.token, resetPasswordExpires: { $gt: Date.now()}}, function(err, user){
      if(err){
          console.log(err);
          //here is where i wish to pass in the link for verification link//
          var link  = '/verification/';
          var message =  'Mail verify token is invalid or has expired, <a href="'+ link +'"> Click here to resend the link</a>.'
          req.flash('error',message)
          return res.redirect('/forgot')
      } else {
          user.active = "true"
          user.save()
          console.log(user.active);
          req.flash('success', 'Your mail have been verified successfully')
          res.redirect('/login');
      }
  })
})

Template Instead of using <%= message %> use this. <%- message %>

<% if(error && error.length > 0) { %>
    <div class="alert alert-danger alert-dismissible deposit-alert" role="alert">
        <div class="container">
          <%- message %> 
        </div>
    </div>
<% } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM