【问题标题】:How to extract a param from a URL using AXIOS?如何使用 AXIOS 从 URL 中提取参数?
【发布时间】:2022-11-13 04:18:56
【问题描述】:

我正在使用 NodeJs、JS 和 AXIOS 为社区访客应用程序实现重置密码功能。实际上,我想为用户实现一项功能,以通过电子邮件请求重置密码链接,但不确定如何从重置密码 URL 中提取参数(令牌)。

例子:

以下是通过电子邮件发送给用户的 URL:

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

然后,我为 mi API 创建了一个 URL 来提取此令牌并在我的数据库中搜索用户以检查用户是否存在,以便我可以更新密码。

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

这是尝试使用 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);

};

`

然后应该由函数接收令牌以搜索用户:

    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();
};

只需提及变量 pass 将从重置密码表单中提取。 :)

我试图包括选项参数,但没有运气。 :(

【问题讨论】:

  • app.get("/reset-password/:token", function(req, res) {var token = req.params.token; ...})
  • 你只是想把那个令牌从路径的尽头拉出来吗? stackoverflow.com/a/13108449/294949
  • 嘿,丹!是的,我正在尝试从路径 localhost:3000/reset-password/xdsnjx 的末尾提取令牌,并将其与我的新密码一起发送到使用 AXIOS 在我的 API 中实现的函数。不确定这是否可能

标签: javascript node.js axios routeparams


【解决方案1】:

我宁愿使用查询参数,以防您需要在链接中包含更多参数:

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

然后在前端使用URLSearchParams

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

// do your axios stuff

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 2011-01-30
    • 2021-06-15
    • 2021-10-07
    • 2019-07-27
    • 2022-12-01
    • 1970-01-01
    • 2014-09-03
    • 2015-05-30
    相关资源
    最近更新 更多