skip to Main Content

I want to make a register function

I try to do like this:

function finish() {

    if (valid) {
        const postData = {
          email: email.value,
          username: username.value,
          password: password.value,
          password2: password2.value
        };
      
        fetch('/register', {
            method: 'POST',
            headers: {
                "Content-type": "aplication/json"
            },
            body:JSON.stringify(postData)
          });
    }
}

and in node js i have this:

app.post('/register', async (req, res) => {
  try {
    const email = req.body.email;
    const newuser = req.body.username;
    const password = req.body.password;
    const repetpasword = req.body.password2;
    console.log(newuser);
    if (checkvalidinput(email, newuser, password, repetpasword)) {
      res.render('startpage')
    } else {
      const message = 'sumphing is wrong'
      res.render('errormessage' , {message: message});
    }

  } catch (error) {
    console.log(error);
  }

});

when i try to display in console the variable "newuser" is dispaly "undefined", how can i solve that?
Any other idea, other metod forsent data from js to node.js?

2

Answers


  1. I think you need to check the fetch and node parts.

    • In the fetch function on js
      be sure you send the correct data (username)

    • If the fetch sends the username data correctly, then see the node.
      Should be json part from the request.

      const data = JSON.parse(req.body);
      const email = data.email;
      const newuser = data.username;
      const password = data.password;
      const repetpasword = data.password2;
      console.log(newuser);

      It should work.

    Login or Signup to reply.
  2. const [creds, setcreds] = useState({
            email:"",
            newuser:"",
            password:"",
            repetpasword :""
        })
    
    const handleChange=(e)=>{
            setcreds({...creds,[e.target.name]:e.target.value})
        }
    
    function finish() {
           if(valid){const postData=creds}
    
            fetch('/register', {
                method: 'POST',
                headers: {
                    "Content-type": "aplication/json"
                },
                body:JSON.stringify(postData)
              });
        }
    }
    

    Give the names (email,newuser,password,repetpasword ) i,e name=’email’ to respective input tags and add the onChange={handleChange} in all the input tags.

    Check by adding a console.log and you are good to go.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search