I'm getting undefined element after get request

Viewed 103

I'm posting and requesting a mail using JSON, when I post the mail, I got no error but the request doesn't work, if I put the same request code in console it returns the requested mail but still return the same error which I mentioned down below

the mail post request(it doesn't show any error)

function send_email() {
 
  var recipient = document.querySelector('#compose-recipients').value;
  var subject = document.querySelector('#compose-subject').value;
  var body = document.querySelector('#compose-body').value;

    var recipients  = recipient.split(',')

    for (email in recipients){
      fetch('/emails', {
          method: 'POST',
          body: JSON.stringify({
              recipients: recipients[email],
              subject: subject,
              body: body
          })
        })
          .then(response => response.json())
          .then(result => {
            // Print result
           console.log(result);
           if (result['error']){
             document.querySelector('#error_msg').innerHTML =
             `<div class="alert alert-danger" role="alert">
                  ${result.error}
              </div>`;
           }
           else {
              load_mailbox('sent');
           }
        });
    }
}

the get request

the console.log works but (sender.innerHTML = emails[mail].sender) return an error

The error is:

Uncaught (in promise) TypeError: Cannot read property 'sender' of undefined at inbox.js:49

fetch(`emails/${mailbox}`)
  .then(response => response.json())
  .then(emails => {
      console.log(emails)
      if(emails.length === 0){
          emails_view.innerHTML += '<p>No emails to see</p>';
      }
      else{
            for(mail in emails){
              console.log(emails[mail].sender);
              var mail = document.createElement("div");
              var sender = document.createElement("h3");
              var subject = document.createElement('p');
              var time = document.createElement('p');
              sender.innerHTML = emails[mail].sender; 
              subject.innerHTML = emails[mail].subject;
              time.innerHTML = emails[mail].timestamp;
            }
        }
  }); 
0 Answers
Related