在下面的代码中,我使用bcrypt来哈希密码并将其存储在用户数组中。使用post => /api/register
初始创建后,登录可以正常工作并返回欢迎消息。用新的/api/register/1,
后的字符串更新密码后,密码确实会更新,但是创建的两个密码登录均失败。感谢您的关注。
const express = require("express");
const app = express();
app.use(express.json());
const bcrypt = require("bcrypt");
const users = [];
app.post("/api/register", async (req, res) => {
// do the registration here
const user = {
id: users.length + 1,
name: req.body.name,
password: req.body.password,
};
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
users.push(user);
res.send(user);
});
app.post("/api/register/:id", async (req, res) => {
const user = users.find((u) => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send("user not found");
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
res.send(user);
});
app.post("/api/login", async (req, res) => {
const user = users.find((u) => u.name === req.body.name);
if (!user) return res.status(404).send("user was not found");
const validPassword = await bcrypt.compare(req.body.password, user.password);
if (validPassword) res.send("welcome" + user.name);
else res.send(user);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening on port ${port}`));
经过数小时的盯着我,我才发现我的问题。 bcrypt.hash(user.password)应该是bcrypt.hash(req.body.password)
您正在本地更新用户变量,但未更新全局数组中的值,因此请尝试以下操作:
app.post("/api/register/:id", async (req, res) => {
const userIndex = users.findIndex((u) => u.id === parseInt(req.params.id));
if (!userIndex) return res.status(404).send("user not found");
const salt = await bcrypt.genSalt(10);
users[userIndex].password = await bcrypt.hash(req.body.password, salt);
res.send(users[userIndex]);
});