首页 > 解决方案 > 尝试在 node.js 中发出 PUT 请求

问题描述

我正在尝试使用 Javascript 向 node.js 发出 PUT 请求。基本上,我要做的是让经过身份验证的用户可以更新电话号码和密码。通常我只是req.body为了让主体用于发出更新请求而使用,但是整个主体都有一个username,passwordphoneNumber. 我只需要更新密码和电话号码。除了登录的注册用户之外,我有一个限制此请求的限制功能,并且我还有一个用于更新的模型功能,即:

function updateUser(changes, id) {
    return db("users")
    .update(changes)
    .where({id})
}

我还试图确保用户决定更新的密码(或他们当前拥有的密码)被散列。我正在使用 bcryptjs 对密码进行哈希处理。我有两个 post 请求,它们都加密密码(这是我的注册功能)和一个比较加密(我的登录功能)的请求。我将包括这两个,以防您需要任何背景信息:

router.post("/register", async (req, res, next) => {
    try {
        const {username, password, phoneNumber} = req.body
        const user = await Users.findBy({username}).first()

        if(user) {
            return res.status(409).json({
                message: "Username is already in use",
            })
        }
        const newUser = await Users.create({
            username,
            password: await bcrypt.hash(password, 14),
            phoneNumber,
        })

        res.status(201).json(newUser)
    } catch (err) {
        next(err)
    }
})


router.post("/login", async(req, res, next) => {
    try {
        const {username, password} = req.body
        const user = await Users.findBy({username}).first()
        
        if(!user) {
            return res.status(401).json({message: "Invalid Username or Password",})
        }

        const passwordValid = await bcrypt.compare(password, user.password)

        if(!passwordValid) {
            return res.status(401).json({message: "Invalid Username or Password",})
        }
        
        const token = jwt.sign({
            userId: user.id,
        }, process.env.JWT_SECRET)
        

        res.cookie("token", token)

        res.json({
            message: `Welcome to your plant page ${user.username}!`
        })
    } catch (err) {
        next(err)
    }
});

当我尝试开始我的 PUT 请求时,我已经开始编写const {phoneNumber, password} = req.body,但我需要在函数中同时使用 phoneNumber 和 password。这是我开始编写代码的示例:

router.put("/:id/updateaccount", restrict(), async(req, res, next) => {
    try {
        const {phoneNumber, password} = req.body
    } catch(err) {
        next(err)
    }
}) 

标签: javascriptnode.jsbcrypt

解决方案


在我班上的某个人寻求帮助后,我明白了这一点。我在正确的轨道上const {phoneNumber, password} = req.body。剩下的就是这个(或者这是所有的代码):

router.put("/:id/updateaccount", restrict(), async(req, res, next) => {
    try {
        const {phoneNumber, password} = req.body
        const userUpdate = await Users.updateUser({
          phoneNumber, password: await bcrypt.hash(password, 14)
         }, req.params.id)
        
        res.status(200).json({
        userUpdate:userUpdate, message: "You have successfully updated your information",
        })
    } catch(err) {
        next(err)
    }
}) 

我再次使用 bcrypt 加密新更新的密码


推荐阅读