mihalkoff

Messenger

Mar 7th, 2022
948
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const url = 'http://localhost:3030/jsonstore/messenger';
  2. const btnSend = document.getElementById('submit');
  3. const btnRefresh = document.getElementById('refresh');
  4. const textarea = document.getElementById('messages');
  5. const author = document.querySelector('#controls input[name = "author"]');
  6. const content = document.querySelector('#controls input[name = "content"]');
  7.  
  8. function attachEvents() {
  9.     btnSend.addEventListener('click', sendMessage);
  10.     btnRefresh.addEventListener('click', getMessages);
  11. }
  12.  
  13. async function sendMessage() {
  14.     if(author.value !== '' || content.value !== '') {
  15.         let obj = {
  16.             author: author.value,
  17.             content: content.value
  18.         }
  19.  
  20.         await fetch(url, {
  21.             method: 'POST',
  22.             headers: {
  23.                 'Content-Type': 'application/json'
  24.             },
  25.             body: JSON.stringify(obj)
  26.         });
  27.  
  28.         author.value = '';
  29.         content.value = '';
  30.     }
  31. }
  32.  
  33. async function getMessages() {
  34.     let res = await fetch(url);
  35.     let data = await res.json();
  36.     textarea.textContent = Object.values(data).map(x => `${x.author}: ${x.content}`).join('\n');
  37. }
  38.  
  39. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment