I keep getting these 2 error, no matter what:
Error: data and hash arguments required & Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I get the first error when comparing hash and plain text. I get the second error in fetchUser.js file when i try to send jwt token in the request headers
Here's my userAuth login route:
router.post('/login', checks.loginChecks, async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let thatOneUser = await User.find({ email });
console.log(thatOneUser);
if (!thatOneUser)
return res.status(403).json({
success: false,
message: `Please enter the correct information!`,
});
bcrypt.compare(password, thatOneUser.password, (err, result) => {
if (!result) {
console.log(err);
return res.status(403).json({
success: false,
message: `Please enter the correct information!`,
err,
});
}
});
const authData = { id: thatOneUser.id };
const authToken = jwt.sign(authData, JWT_SECRET);
res.json({ success: true, message: 'User has been logged!', authToken });
} catch (error) {
res.status(500).json({
success: false,
message: 'Error occured during logging the user',
error,
});
console.log(error);
}
});
and here's my fetchUser.js:
const jwt = require('jsonwebtoken');
const JWT_SECRET = 'jwtsecretabc123';
const fetchUser = (req, res, next) => {
// Get the user from the jwt token and add id to req object
const token = req.header('auth-token');
console.log(token);
if (!token)
return res.status(401).json({
success: false,
message: 'Please authenticate using a valid token!',
});
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded.user;
console.log(decoded.user, ' I am decoded id!');
next();
} catch (error) {
return res
.status(401)
.json({ success: false, message: 'failed to decode the token' });
}
};
module.exports = fetchUser;
when i make request to localhost:5000/api/auth/login, it works the first time, but doesn't work the second time.
None of the other requests (register, getUserData) are working either. Any help will be appreciated!