Linked Questions

Popular Questions

How to get value from URL using Node.js and Express?

Asked by At

I am trying to get the token value from the following URL http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8. I have a get request that checks if the token is valid and redirects the user to a reset password screen. I also have a post request but when I console req.params.token, it outputs :token instead of e3b40d3e3550b35bc916a361d8487aefa30147c8. I am wondering if the form action is correct but don't know how to get the token value from it.

Reset Password Get Request

router.get('/reset/:token', (req, res) => {
  console.log(req.params.token) // e3b40d3e3550b35bc916a361d8487aefa30147c8
  User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: {
      $gt: Date.now() 
    }
  }, (err, user) => {
    if (!user) {
      req.flash('error_msg', 'The password reset token is invalid or has expired.')
      return res.redirect('/users/forgot')
    }
    res.render('reset')
  })
})

reset.ejs

<% include ./partials/messages %>
<form action="/users/reset/:token" method="POST">
    <div class="form-group">
    <label for="password">Password</label>
    <input type="password" id="password" name="password" class="form-control" placeholder="Please enter a password."
        value="<%= typeof password != 'undefined' ? password : '' %>" />
    </div>
    <button type="submit" class="btn btn-primary btn-block">Register</button>
</form>

Reset Password Post Request

router.post('/reset/:token', (req, res) => {
  console.log(req.params.token) // :token
  User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: {
      $gt: Date.now() 
    }
  }, (err, user) => {
    if (!user) {
      req.flash('error_msg', 'The password reset token is invalid or has expired.')
      return res.redirect('/users/forgot')
    }

    user.password = req.body.password;
    user.resetPasswordToken = undefined;
    user.resetPasswordExpires = undefined;

    user.save(function (err) {
      req.flash('success_msg', 'Working.')
      return res.redirect('/users/login')
    })
  })
})

Related Questions