Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const url = 'http://localhost:3030/jsonstore/messenger';
- const btnSend = document.getElementById('submit');
- const btnRefresh = document.getElementById('refresh');
- const textarea = document.getElementById('messages');
- const author = document.querySelector('#controls input[name = "author"]');
- const content = document.querySelector('#controls input[name = "content"]');
- function attachEvents() {
- btnSend.addEventListener('click', sendMessage);
- btnRefresh.addEventListener('click', getMessages);
- }
- async function sendMessage() {
- if(author.value !== '' || content.value !== '') {
- let obj = {
- author: author.value,
- content: content.value
- }
- await fetch(url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(obj)
- });
- author.value = '';
- content.value = '';
- }
- }
- async function getMessages() {
- let res = await fetch(url);
- let data = await res.json();
- textarea.textContent = Object.values(data).map(x => `${x.author}: ${x.content}`).join('\n');
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment