Im building the login functionality for my application with an asynchronous call to my API. My issue is that even though express is throwing an error, .then() is still being run with the error and not the actual user and token response. I am not sure why the login function is not 'catching' the error and instead running the code inside .then().
My express function:
// express funciton to login a user
app.post('/api/users/login', (req, res) => {
const { email, password } = req.body
database.getUser(email, password, (error, user) => {
console.log(error)
if (error) {
res.send({ error })
//errors are being handled here and are returned in the result of my
frontend API call
return
}
const token = jwt.generateToken({ userId: user.id, name: user.name, email: user.email })
res.send({ token: token, user:user })
})
})
//getUser function with mySQL query
function getUser(email, password, callback) {
const query = `
SELECT id, name, email, password
FROM users
WHERE email = ?
`
const params = [email]
connection.query(query, params, (error, results, fields) => {
if (!results || results.length === 0) {
callback(Error("Email is incorrect"))
return
}
const user = results[0]
bcrypt.compare(password, user.password, (error, same) => {
console.log(error)
if (error) {
callback(error)
return
}
if (!same) {
callback(Error("Password is incorrect"))
return
}
callback(null, user)
})
})
}
exports.getUser = getUser
My login function in Next.js:
const login = async ({ email, password }) => {
return await axios.post('http://localhost:4200/api/users/login', {
email: email,
password: password
})
.then((result) => {
//when backend throws error, they are contained here as "result.error" still running these lines of code
sessionStorage.setItem('token', result.data.token);
axios.defaults.headers.common['Authorization'] = "Bearer " result.data.token;
console.log('user signed in');
})
.catch((err) => {
//want errors to be directed here instead so I can properly handle them within the UI
console.error("Username or password is incorrect!!")
})
};
CodePudding user response:
Where you have .catch(error)
will only error if there is an issue with the axios promise itself being able to complete.
In this case, the axios promise is completing correctly, however, you are then returned a valid error code for why the login cannot complete.
Therefore one approach would be within your .then(result)
function to look for that type of result and do something.
So something like
.then((result) => {
if (result.error) { ... return an error message to user ... }
else {
sessionStorage.setItem('token', result.data.token);
axios.defaults.headers.common['Authorization'] = "Bearer "
result.data.token;
console.log('user signed in');}
})