使用bcryptjs库并在执行Put请求时遇到2个问题:
1-在失眠/邮递员上,服务器返回哈希密码,但在客户端检查控制台工具上返回“未哈希”。
2-我无法使用新的密码凭证执行登录。
请在服务器代码上出现任何可见的语法错误或快速建议?谢谢!
客户侧代码:
function DevUpdateForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [techs, setTechs] = useState("");
async function updateUser(e) {
e.preventDefault()
const dataUpdate = { name, email, password, techs}
const response = await api.put(`/devs/${dev._id}`, dataUpdate);
console.log(response);
setName('');
setEmail('');
setPassword('');
setTechs([]);
}
return (
<div className="update-profile">
<strong>Alterar</strong>
<img src={dev.avatar_url} alt={dev.name}/>
<form onSubmit={updateUser} >
<div className="input-block">
<label htmlFor="name">Nome:</label>
<input
name="name"
id="name"
type="text"
placeholder={"Alterar nome"}
value={name}
onChange={e => setName(e.target.value)}
/>
</div>
<div className="input-block">
<label htmlFor="email">E-mail:</label>
<input
name="email"
id="email"
type="text"
placeholder={"Alterar email"}
value={email}
onChange={e => setEmail(e.target.value)}
/>
</div>
<div className="input-block">
<label htmlFor="password">Senha:</label>
<input
name="password"
id="password"
type="password"
placeholder={"Digite nova senha"}
value={password}
onChange={e => setPassword(e.target.value)}
/>
</div>
<div className="input-block">
<label htmlFor="techs">Techs:</label>
<input
name="techs"
id="techs"
type="text"
placeholder={"Alterar tecnologias"}
value={techs}
onChange={e => setTechs(e.target.value)}
/>
</div>
<button type="submit" >Salvar</button>
</form>
</div>
)
}
export default DevUpdateForm;
服务器端更新控制器:
async update(req, res, next) {
try {
const { name, email, password, techs } = req.body;
const { _id } = req.params;
const techsArray = parseStringAsArray(techs);
let dev = await Dev.findByIdAndUpdate(_id, {
name,
email,
password,
techs: techsArray
},
{new: true});
dev = await Dev.findById(_id)
dev.password = await bcrypt.hash(dev.password, 8)
if (dev !== null) {
res.status(200).send({
data: dev,
message: "Dev has been updated!"
});
} else {
res.status(404).end();
}
} catch (error) {
next(error)
}
},
路线:
routes.put('/devs/:_id', DevController.allowIfLoggedin, DevController.grantAccess('updateAny', 'profile'), DevController.update);
找到模型并为用户模型设置新值之后。您必须执行。save()语句以更新现有更改。
async update(req, res, next) {
try {
const { name, email, password, techs } = req.body;
const { _id } = req.params;
const techsArray = parseStringAsArray(techs);
let dev = await Dev.findByIdAndUpdate(_id, {
name,
email,
password,
techs: techsArray
},
{new: true});
dev = await Dev.findById(_id)
dev.password = await bcrypt.hash(dev.password, 8)
dev.save();// add this to save new password
if (dev !== null) {
res.status(200).send({
data: dev,
message: "Dev has been updated!"
});
} else {
res.status(404).end();
}
} catch (error) {
next(error)
}
},