skip to Main Content

When I try to print console.log(body.email), the console says its undefined, but when I call console.log(body) it returns me {"email":"[email protected]","password":"Password"}

here is the code below:

 document.getElementById("SingupForm").addEventListener('submit', evt =>{
      evt.preventDefault()
      const form = evt.target
      const body =JSON.stringify({
        email: form.elements.email.value,
        password: form.elements.password.value,
      }) 
      console.log(body.email)
    })

I’ve tried to rename the strings and add them to an external script, but it didn’t work.

2

Answers


  1. body is a string, but you’re accessing it like an object.

    assign it without the calling to JSON.stringify if you want to keep it as an object

       const body = {
            email: form.elements.email.value,
            password: form.elements.password.value,
       }
    
    Login or Signup to reply.
  2. In your code body is a string and not an object and that is why you get undifined for the email property.

    Try this code:

    document.getElementById("SingupForm").addEventListener('submit', evt =>{
          evt.preventDefault()
          const form = evt.target
          const body ={
            email: form.elements.email.value,
            password: form.elements.password.value,
          }
          console.log(body.email)
        })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search