PUT请求在Express.js中使用mongoose更改用户密码时不起作用。

huangapple go评论54阅读模式
英文:

PUT request not working for changing user password in Express.js with mongoose

问题

我目前正在开发一个 Express.js 应用程序,其中我有一个用于更改用户密码的端点。当我使用 POST 请求时,该端点正常工作,但当我切换到 PUT 请求时,它不起作用。我不确定可能导致这个问题。在 Postman 中,我收到一个 "500 - 内部服务器错误"。

以下是我的代码:

// 路由定义
router.post("/change-password", userController.changePassword);

当我将上面的代码更改为使用 router.put 而不是 router.post 时,请求不再起作用。我已经检查了请求方法确实设置为 PUT,并且我将请求发送到了正确的 URL(/user/change-password)。

// 更改用户密码
const changePassword = async (req, res) => {
  // 从请求头中获取令牌
  const token = req.headers.authorization;
  if (!token) {
    return res.status(401).json({ message: "未提供令牌。" });
  }

  // 从请求体中获取 JSON
  const { oldPassword, newPassword } = req.body;

  try {
    // 验证令牌并提取有效载荷
    const decoded = verifyToken(token);
    const { _id } = decoded;

    // 根据 id 查找用户
    const user = await User.findById(_id);
    if (!user) {
      return res.status(404).json({ error: "未找到用户" });
    }

    // 检查密码是否正确
    const isPasswordValid = await user.comparePassword(oldPassword);
    if (!isPasswordValid) {
      return res.status(401).json({ message: "凭据无效。" });
    }

    // 更新用户密码
    user.password = newPassword; // 用户模型中已完成密码哈希处理
    await user.save();

    return res.status(200).json({ message: "密码成功更改。" });
  } catch (error) {
    res.status(500).json({ error: "内部服务器错误" });
  }
};

我正在使用 Express.js 版本 4.18.2,并使用 Postman 等工具测试端点。

我不确定可能导致这个问题,或者在 Express.js 中是否需要配置不同的 PUT 请求。对于如何排除此问题的任何见解或建议都将不胜感激。谢谢!

英文:

I'm currently working on an Express.js application where I have an endpoint for changing a user's password. The endpoint works perfectly fine when using a POST request, but it doesn't work when I switch to a PUT request. I'm not sure what could be causing this issue. I am getting in postman a "500 - Internal server Error"

Here's my code:

// Route definition
router.post("/change-password", userController.changePassword);

When I change the above code to use router.put instead of router.post, the request doesn't work anymore. I've checked that the request method is indeed set to PUT, and I'm sending the request to the correct URL (/user/change-password).

// Change a user's password
const changePassword = async (req, res) => {
  // Get the token from the request headers
  const token = req.headers.authorization;
  if (!token) {
    return res.status(401).json({ message: "No token provided." });
  }

  // JSON from the request body
  const { oldPassword, newPassword } = req.body;

  try {
    // Verify the token and extract the payload
    const decoded = verifyToken(token);
    const { _id } = decoded;

    // Find the user by id
    const user = await User.findById(_id);
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }

    // Check if the password is correct
    const isPasswordValid = await user.comparePassword(oldPassword);
    if (!isPasswordValid) {
      return res.status(401).json({ message: "Invalid credentials." });
    }

    // Update the user's password
    user.password = newPassword; // Password hashing is done in the User model
    await user.save();

    return res.status(200).json({ message: "Password changed successfully." });
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
};

I'm using Express.js version 4.18.2 and testing the endpoint using tools like Postman.

I'm not sure what could be causing this issue or if there's anything specific that needs to be configured differently for PUT requests in Express.js. Any insights or suggestions on how to troubleshoot this would be greatly appreciated. Thank you!

答案1

得分: 0

我已经找到了解决方法。原来是我的端点URL引起了问题。问题是URL需要一个带有参数的前缀,用于PUT请求。在我的情况下,我的PUT请求结构如下:

router.put("/change-password", userController.changePassword);

添加了前缀"/:id"后,Express.js不再报错。新的URL如下:

router.put("/change-password/:id", userController.changePassword);

希望这个答案能帮助你们中的一些人。特别感谢评论中的帮助,帮助我调试和学习Express.js!

英文:

I have found a solution to my problem. It turns out that the URL from my endpoint created the problem. The problem was that the URL required a prefix with a parameter for a PUT request. In my case, my PUT request was structured as follows:

router.put("/change-password", userController.changePassword);

After adding the prefix "/:id", Express.js no longer threw an error. The new URL looks like this:

router.put("/change-password/:id", userController.changePassword);

I hope this answer can help some of you. Special thanks to for the comment, helping me to debug and lern Express.js!

huangapple
  • 本文由 发表于 2023年6月22日 02:22:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定