I am trying to have my server reject the signup request if the user tries to sign up with an existing account. However, I cant seem to reject it properly and pass the error message to my client side.
//server.js
app.post('/signup', (req, res) => {
const email = req.body.email
const plainTextPassword = req.body.password;
//check if user already exists
User.find({ email: email }, (err, existingUser) => {
//account doesnt exist
if (existingUser.length === 0) {
bcrypt.hash(plainTextPassword, saltRounds, async (err, hash) => {
try {
const user = new User({
email: email,
password: hash
});
let result = await user.save();
if (result) {
res.send(result)
}
} catch (e) {
res.send(e);
}
})
} else {
//notify user that account exists
return Promise.reject(new Error('Account already exists'))
}
})
})
//reduxSlice.js
export const signup = createAsyncThunk(
'userAuth/signup',
async (payload, thunkAPI) => {
const { email, password } = payload
try {
const result = await fetch(
signupPath, {
mode: 'cors',
credentials: 'include',
method: "post",
body: JSON.stringify({ email, password }),
headers: {
'Content-Type': 'application/json'
}
}
)
return result.json()
} catch (error) {
console.log(error) //this line executes
}
}
)
From my reduxdev tools, my signup is still fulfilled EVEN though I rejected it from my server. Also, my server crashes after one attempt, which leads me to suspect there is an uncaught error.