My front end is done in React Native and backend in nodejs. It is an application that asks the user to register (email, password, name, email, ...) and then the data is sent to a database (mongodb) using mongoose.
In my front end; when the user presses the button SignUp, it will call a function names "Submit" that you can find below:
const Submit = async (fname, email, pwd, confpwd) => {
if (String(pwd).localeCompare(String(confpwd)) == 0) {
let result = await fetch('http://127.0.0.1:2000/api/user/register', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(
{
name: fname.fname,
email: email.email,
password: pwd.pwd
}
)
})
console.log("RESULT : " + JSON.stringify(result))
} else{
console.log('NOT SAME PASSWORD')
}
};
It just takes in the firstname, email and password entered by the user and uses fetch to post it to the API. Everything works, except the last line : console.log("this is the result : " + JSON.stringify(result)). It always returns an empty json.
The register route in my backend is the following:
//REGISTER
router.post('/register', async (req, res) => {
//Check the input of the user before we make a user
const {error} = registerValidation(req.body)
if (error) {
console.log('Error1')
return 'Error1'
}
console.log('1&')
//Check if the user is already in the database
const emailExist = await User.findOne({email : req.body.email});
if(emailExist) {
console.log('Error2')
return 'Error2'
}
console.log('2&')
//Hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt)
console.log('3&')
//Create a new user
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
console.log('4&')
//user.save();
try{
const saveUser = await user.save();
res.send(saveUser);
console.log('5&')
}catch(err){
res.send(err)
}
});
Before saving it to the databse it checks the validation and if the email already exists in the database.
It successfully sends the data to the database when the first two conditions are met and if email is already used and the validation format is not correct it does not put it in the dataabse.
However, when the validation format is not correct or the emaoil is already used, I would like my fetch in my front end to let me know. So I thought that putting my fetch in a variable it would output something if it did not work. However, it always sends back an empty json even when the fetch did not work. So, how can I pass a variable from my backend to my frontend ?
Normally in postman this is what I receive when the email already exists. How can I receive this on my frontend ?
