mardi 27 août 2019

My forEach does not want to run my if-statement

I'm making a chat app API in Node.js using express. I link my front-end with a fetch but my if-statement is not working and I don't know what I'm doing wrong here...

I'm doing a fetch() to my API, http://localhost:3000/api/v1/chat/:id. Then I want to forEach over my database but there is something wrong in the if-statement because it wont run the code, it goes to the catch and I get the err. I'm saving "reciever" in my localeStorage, after that I'm pasting the id from the reciever behind my url. At last I want a foreach running over my database to check all the messages posted from the different users. I've made the id-statement to see if the message is from the sender or from the reciever.

if (e.target.classList.contains("user")) {
          let reciever = e.target.getAttribute("data-id");
          console.log(reciever);
          localStorage.setItem("reciever", reciever);
          document.querySelector(".title__user").innerHTML = e.target.innerHTML

          fetch('http://localhost:3000/api/v1/chat/' + reciever, {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }).then(result => {
            return result.json();
          }).then(json => {
            document.querySelector(".messages").innerHTML = "";
            json.data.messages.forEach(message => {
            if(messages.sender === localStorage.getItem('id')){
              let message = `
                <div class="wrapper" data-id="${message._id}"><span class="message right" data-id="${message._id}">${message.text}</span></div>
              `;
            } else{
              let message = `
                <div class="wrapper left" data-id="${message._id}"><span class="message" data-id="${message._id}">${message.text}</span></div>
              `;
            }
            document.querySelector(".messages").innerHTML += message;    
            });
          }).catch(err => {
            console.log("Aiaiaiai 😢")
            //window.location.href = "login.html";
        })

      } 

The if-statement just does not want to run and I don't know what I'm doing wrong here.

Aucun commentaire:

Enregistrer un commentaire