javascript - 尝试在 node.js 中发出 PUT 请求
问题描述
我正在尝试使用 Javascript 向 node.js 发出 PUT 请求。基本上,我要做的是让经过身份验证的用户可以更新电话号码和密码。通常我只是req.body
为了让主体用于发出更新请求而使用,但是整个主体都有一个username
,password
和phoneNumber
. 我只需要更新密码和电话号码。除了登录的注册用户之外,我有一个限制此请求的限制功能,并且我还有一个用于更新的模型功能,即:
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)
}
})
解决方案
在我班上的某个人寻求帮助后,我明白了这一点。我在正确的轨道上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 加密新更新的密码
推荐阅读
- go - 如何向 map[string]interface{} 添加新值
- java - 使用名称 TABHIBERNATE_SEQUENCES 生成 HIBERNATE_SEQUENCES 表
- sql - 在通常的 FROM 子句中添加 JOINS
- c# - 我将如何添加键绑定切换功能?
- java - 深色模式下的 Android 颜色
- html - 如何使锚点与 nodemailer 电子邮件正文一起使用
- c++ - Qt 行导致奇怪的错误:Cmd.exe exited with code -20
- python - 如何从“taskSubmittedEventDetails”中获取 getexecutionhistory api 的 stepid
- azure - 使用内置系统变量创建 Powershell 环境变量
- kendo-grid - 如何删除 Kendo grid.dataSource 中的更改?