0

I'm implemeting a reset password feature for a neighborhood vistors app using NodeJs, JS and AXIOS. Actually, I want to implement a feature for the users to request a reset password link via e-mail but not sure how to extract a param (token) from the reset password URL.

Example:

Here is the URL sent to the user via email:

http://localhost:3000/reset-password/xdsnjx -> I sent a random token as a param in this URL

Then, I created a URL for mi API to extract this token and search the user in my data base to check if the users exist so I can update the password.

API URL: http://localhost:3000/api/v1/admin/updatepass/

Here is the function to try to patch this user using AXIOS:

`

const changePassword = async (pass) => {
  try {
    const res = await axios({
      method: 'PATCH',
      url: `http://localhost:3000/api/v1/admin/updatepass/`,
      params: {
        token: -> Random token extracted from the URL http://localhost:3000/reset-password/xdsnjx ,
      },
      data: {
        pass -> password that will be updated,
      },
    });
    console.log(res);

};

`

The token then should be received by a function to search for the user:

    const updatePassword = async (req, res, next) => {
  const { token } = req.params;
  const { password } = req.body;

  const user = await User.findOne({
    where: { token },
    attributes: ['id', 'password', 'token'],
  });

  const salt = await bcrypt.genSalt(10);
  user.password = await bcrypt.hash(password, salt);
  user.token = null;
  user.confirmed = true;
  await user.save();
  return next();
};

Just to mention the variable pass will be extracted from a reset password form. :)

I've tried to include the option params, but no luck. :(

  • `app.get("/reset-password/:token", function(req, res) {var token = req.params.token; ...})` – Heiko Theißen Nov 12 '22 at 19:30
  • Are you just looking to pull that token off the end of the path? https://stackoverflow.com/a/13108449/294949 – danh Nov 12 '22 at 19:39
  • Hey danh! Yes, I'm trying to pull the token off from the end of the path http://localhost:3000/reset-password/xdsnjx and send it along with my new password to the function implemented in my API using AXIOS. Not sure if this is even possible jejeje – Juan Arias Nov 12 '22 at 19:42
  • Does this answer your question? [Last segment of URL with JavaScript](https://stackoverflow.com/questions/4758103/last-segment-of-url-with-javascript) – Michael M. Nov 12 '22 at 20:42

1 Answers1

1

I would rather user a query parameter, in case you need to include more parameters in the link:

http://localhost:3000/reset-password?code=xdsnjx 

Then in the frontend use URLSearchParams:

const params = new URLSearchParams(window.location.search);
const code = params.get('code');

// do your axios stuff
moonwave99
  • 21,957
  • 3
  • 43
  • 64