0

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 ?

enter image description here

3 Answers 3

2

On your backend,

You should return a valid HTTP status code and json payload in order to be correctly understood by your front-end.

For invalid inputs you can return a 400 Bad Request with a proper json description and return 200 OK for valid responses.

// for errors
res.status(400).send({error: 'Email already exists' })

// for successful responses
res.status(200).send({result: 'success' })

In your front-end, then you can parse this status code to understand if it is a valid / invalid request and parse payload to show any proper message to your users:

const Submit = async (fname, email, pwd) => {
  try {
    let response = 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,
        },
      ),
    });
    const statusCode = response.status;
    const { error, result } = response.json();
    // do whatever you want with this info here
  } catch (err) {
    console.log(err);
  }
};

Also, keep in mind that since fetch is running asynchronously, you should use await prefix in an async function like above or use Promises:

Sign up to request clarification or add additional context in comments.

7 Comments

The first code still gives an empty string and in the second code there a syntax error which I cannot seem to find ...
have you ever tested your backend api with postman? is it still returning an empty string?
Yes on postman it works and returns an empty string as well!!
So I would like to know how it is possible to pass paramaters between the backend and the frontend to be able to tell my front end how to act when there is a particular error
For the second code this is my output : this is the result : [object Promise] but it does not help me much
|
1

fetch returns a promise you need to handle it use async/await

const Submit = = async (fname, email, pwd) => {
    const body = JSON.stringify({
        name: fname.fname,
        email: email.email,
        password: pwd.pwd
    })

    const headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    }

    const settings = {
        method: 'POST',
        headers,
        body
    };

    try {
        const fetchResponse = await fetch(`http://127.0.0.1:2000/api/user/register`, settings);
        const data = await fetchResponse.json();
        return data; // your response data
    } catch (e) {
        console.log(e)
        return e; // handle your error here
    }

}

8 Comments

Are you sure it is correct? becaise it is not working on my code
what you get when console logging the data console.log(data) before the returned statement
It returns my data that is stored in my database later but if there are one of the conditions not working (ex : email already used) then it does not return anything and my goal is to pass a variable from my backend to my frontend to tell me which condition did not pass
I edited my questions with a picture of postman to make it more clear
the problem is you return plan text from the server and trying to parse it, if you are using express one the server do res.json({ your response data here });
|
0

fetch API in submit function is async means console.log() get execute before fetch complete.

you can use asyn/await to get fetch response and get that response to console.log().

// async function
async function fetchAsync () {
  // await response of fetch call
  let response = await fetch('https://api.github.com');
  // only proceed once promise is resolved
  return response;
}

1 Comment

what is data corresponding to?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.