I try to make login with node.js and next.js but I can't return token. I am working with mysql database.
Here is my code. I try with console.logs and its stuck in part where i select from database. My model is simple just username and password. pasword is bcrypt.
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import db from '../../db/db'
export default async (req, res) => {
if(req.method === "POST"){
console.log("POSTED");
const { username, password } = req.body;
console.log(req.body)
try {
let user = await db.execute("SELECT * FROM user WHERE username = ?", [username]);
console.log("eeeee",user)
if (!user) {
return res
.status(400)
.json({ errors: [{ msg: 'Invalid Credentials' }] });
}
const isMatch = await bcrypt.compare(password, user.password);
console.log(isMatch);
if (!isMatch) {
return res
.status(400)
.json({ errors: [{ msg: 'Invalid Credentials' }] });
}
const payload = {
user: {
id: user.iduser,
username: user.username
},
};
console.log("tokeeeeen: ",token)
jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: 24 * 60 * 60 * 1000 },
(err, token) => {
if (err) console.log(err);
console.log(token);
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
}
}
When calling bcrypt-compare I get the following error: 'data and hash arguments required'