EntropyStarRover

01.Messenger

Mar 1st, 2021 (edited)
544
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.  
  3.     let authorInput = document.getElementById("author");
  4.     let contentInput = document.getElementById("content");
  5.     let submitBtn = document.getElementById("submit");
  6.     let refreshBtn = document.getElementById("refresh");
  7.     let messagesArea = document.getElementById("messages");
  8.     getAllMessages();
  9.  
  10.     refreshBtn.addEventListener("click", getAllMessages);
  11.     submitBtn.addEventListener("click", submitMessage);
  12.  
  13.     function getAllMessages() {
  14.         let requestOptions = {
  15.             method: 'GET',
  16.             redirect: 'follow'
  17.         };
  18.  
  19.         fetch("http://localhost:3030/jsonstore/messenger", requestOptions)
  20.             .then(response => response.json())
  21.             .then(result => displayMessages(result))
  22.             .catch(error => console.log('error', error));
  23.     }
  24.  
  25.     function displayMessages(r) {
  26.         messagesArea.innerHTML = "";
  27.         let messagesArr = Object.values(r);
  28.         messagesArr.forEach(m => {
  29.             messagesArea.textContent += `${m.author}: ${m.content}\n`
  30.         });
  31.         contentInput.value = "";
  32.         authorInput.value = "";
  33.  
  34.     }
  35.  
  36.     function submitMessage() {
  37.         let authorV = authorInput.value;
  38.         let contentV = contentInput.value;
  39.  
  40.         let myHeaders = new Headers();
  41.         myHeaders.append("Content-Type", "application/json");
  42.  
  43.         var raw = JSON.stringify({
  44.             "author": authorV,
  45.             "content": contentV
  46.         });
  47.  
  48.         var requestOptions = {
  49.             method: 'POST',
  50.             headers: myHeaders,
  51.             body: raw,
  52.             redirect: 'follow'
  53.         };
  54.  
  55.         fetch("http://localhost:3030/jsonstore/messenger", requestOptions)
  56.             .then(response => response.json())
  57.             .then(result => getAllMessages())        
  58.             .catch(error => console.log('error', error));
  59.     }
  60.  
  61.  
  62. }
  63.  
  64. attachEvents();
RAW Paste Data