尝试使用bcrypt将用户保存到mySql中。但是返回错误:需要data和salt参数。
这是我的代码
授权控制器:
export const register = (req, res) => {
//CHECK EXISTING USER
const q = "SELECT * FROM user WHERE email = ? OR username = ?";
db.query(q, [req.body.email, req.body.username], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length) return res.status(409).json("User already exists!");
//Hash the password and create a user
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
const values = [req.body.username, req.body.email, hash];
db.query(q, [values], function (err, data) {
if (err) return res.status(500).json(err);
return res.status(200).json("User has been created.");
});
});
};
如您所见,我已经定义了salt和hash byconst salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
我不知道为什么要返回Error:需要data和salt参数。
下面是返回的错误:
错误:在Object. hashSync(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/bcrypt/bcrypt. js:91:15)在Query中需要data和salt参数。(file:///Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/controllers/auth.js:14:27)。(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/Connection. js:五二六:10)在查询。_callback(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/Connection. js:四百八十八:16)在查询。顺序。end(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/protocol/sequences/Sequence. js:八十三:24)在查询。_handleFinalResultPacket(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/protocol/sequences/Query. js:一百四十九:(8)查询。EofPacket(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/protocol/sequences/Query. js:一百三十三:(8)协议。_parsePacket(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/protocol/Protocol. js:二九一:(23)解析器。_parsePacket(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/protocol/Parser. js:四百三十三:10)在Parser。write(/Users/rickyyeung/Desktop/nodejsProject/rick20230510booking/api/node_modules/mysql/lib/protocol/Parser. js:四十三:10)rickyyeung@Rickys-MacBook-Air api %
1条答案
按热度按时间jv4diomz1#
我看到两个问题,
one:你只传递了一个值给sql,但需要传递3个值:
当将值插入到数据库中时,在这种情况下,您只提供了一个值
VALUES (?)";
,而它应该像VALUES (?,?,?)";
一样匹配传入const values
的参数:req.body.username, req.body.email, hash
关于hash问题:
req.body.password
似乎是空的。检查是否为null或undefined。